JoeTidee JoeTidee - 1 year ago 116
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download