JoeTidee JoeTidee - 4 months ago 43
React JSX Question

How to create a dynamic prop name in React?

Is it possible to create the name of a prop dynamically? For example:

let dynamicPropName = "someString";

<MyComponent dynamicPropName="some value" />

so that inside MyComponent, this.props.someString exists.


If you are using es6, you can define the dynamic prop:

let dynamicProps = {"dynamicKey":"someString", "dynamicKey2":"someString"};


let someVariable = "xyz";
dynamicProps[someVariable] = value;

then use the spread operator:

<MyComponent {...dynamicProps} />

Inside MyComponent -

let props = ...this.props;

Now you can use props.keys to get all prop names.