dboyd68
dboyd68

Reputation: 1114

Stateless React how to pass key

I am unsure how to pass a key to a stateless react component

MyComponent: (props) => {
        return(<span>{props.somevalue}</span>);
    }


aCollection.map((value,index)=> <MyComponent somevalue={value});

Doing this will result in the key warning.

So I tried to pass in key via a prop

aCollection.map((value,index)=> <MyComponent key={index} somevalue={value});


MyComponent: (props) => {
            return(<span key={this.props.key} >{props.somevalue}</span>);
     }

However I get the error https://facebook.github.io/react/warnings/special-props.html

How am I meant to pass/use the key in my stateless component?

Upvotes: 2

Views: 3448

Answers (3)

ibasoni
ibasoni

Reputation: 164

You can try the following:

<React.Fragment key={item.id}>{SomeFunctionComponent(item)}</React.Fragment>

From the docs:

Fragments declared with the explicit syntax may have keys.

Can be found here

Upvotes: 2

cxxsn
cxxsn

Reputation: 188

According to React docs, a key should be provided for list component items.

You only need pass the key to react component, you don't need to use it in the component, like access the key with props.key.

check out Basic List Component.

Upvotes: 2

Shubham Khatri
Shubham Khatri

Reputation: 281894

As the error says that special props (ref and key) which are used by React, and are thus not forwarded to the component, so you can't pass the prop by name key and yes in order to eliminate warning you need to define the key, so just rename the prop while sending it to MyComponent. Also I believe you must use the prop in your stateless component like props.index and not this.props.index.

aCollection.map((value,index)=> <MyComponent index={index} somevalue={value});


MyComponent: (props) => {
            return(<span key={props.index} >{props.somevalue}</span>);
     }

You only need to define key to the span so use it as key={props.index}. It should eliminate the warning.

Upvotes: 0

Related Questions