I'm wondering if it's possible to do the following in JSX (this code does not work, just an example of what I'm trying to do):
const propKey = 'someProp';
const jsx = <MyComponent [propKey]="some value" />;
// evaluates to <MyComponent someProp="some value">
I'm using babel es2015 stage-1, so I could spread a dictionary like this:
const extraProps = {[propKey]: 'some value'};
const jsx = <MyComponent {...extraProps} />
but that seems too clunky for just one prop. I'm not looking to use React.createElement; all my classes are es6 classes. Thanks!
You can create in the JSX an object using the computed property names, and spread it:
const propKey = 'someProp';
const jsx = <MyComponent { ...{ [propKey]: "some value" } } />;
JSX is syntactic sugar for calling React.createElement
. So one solution is to call React.createElement
directly:
const element = React.createElement(MyComponent, {[propKey]: 'some value'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With