JoeTidee JoeTidee - 3 days ago 6
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.

Answer

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

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

or

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.

Comments