redconservatory
redconservatory

Reputation: 21934

ReactJS: adding my own props to another component

Is it possible (or even a good idea) to add my own props to another React component, like:

<SomeCustomComponent myOwnParam={handler}>

Upvotes: 2

Views: 335

Answers (2)

Daniel Bank
Daniel Bank

Reputation: 3899

As mentioned by Tyrsius, it really depends on the implementation of SomeCustomComponent. If the component does not use the myOwnParam prop anywhere, passing it won't accomplish anything. On the other hand, some React components might use JSX spread attributes to reference props not directly enumerated in the code.

As an example, the following implementation of SomeCustomComponent would pass your myOwnParam prop down to its child div:

class SomeCustomComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    var {customComponentProp, ...other } = this.props;
    return (
      <div customComponentProp={customComponentProp} {...other}></div>
    );
  }
}

So again, it depends on the implementation of SomeCustomComponent what will happen.

See Transferring Props documentation for more details: https://facebook.github.io/react/docs/transferring-props.html

Upvotes: 4

Kyeotic
Kyeotic

Reputation: 19857

This won't cause an error, but unless SomeCustomComponent is looking for this prop nothing will be done with it. It is possible for a component to loop over its props, so this could be a usable strategy, but I am not sure what you would do with it. You couldn't define anything but iteration logic over properties that you don't know in advance.

Upvotes: 2

Related Questions