Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

key is not available as prop in the Child component in ReactJs

Tags:

reactjs

jsx

I have a parent component in which below component is producing dynamically in map function as below:

const renderListing = this.props.listing.map(function(list, index) {
        return (
          <Listing
            key={index}
            title={list.title}
            totalWorkers={list.totalWorkers}
          />
        );
      }, this);

In this <Listing /> component, I have a Checkbox from react-md as below:

import { Checkbox } from "react-md";
class Listing extends React.Component {
  render() {
    return (
<Checkbox id="`listSector-${this.props.key}`" name="list-sector" />
   );
  }
}

I wanted to give the props named key concatenated with id="listSector-0" , id="listSector-1" and so on.

I have tried string-literals but all invain.

Can anyone know that how to give dynamic this.props.key concatenated with id of the checkbox ?

Thanks

like image 818
Owais Avatar asked Feb 05 '23 03:02

Owais


2 Answers

'key' and 'ref' are reserved words that are not allowed to be passed as props. You can pass another prop with the same value

const renderListing = this.props.listing.map(function(list, index) {
    return (
      <Listing
        key={index}
        keyId={index}
        title={list.title}
        totalWorkers={list.totalWorkers}
      />
    );
  }, this);

and use it like

<Checkbox id="`listSector-${this.props.keyId}`" name="list-sector" />
like image 117
Shubham Khatri Avatar answered Feb 07 '23 02:02

Shubham Khatri


Most props on a JSX element are passed on to the component, however, there are two special props (ref and key) which are used by React, and are thus not forwarded to the component.

Special Props Warning – React

like image 29
Jehong Ahn Avatar answered Feb 07 '23 03:02

Jehong Ahn