Set Prop key dynamically JSX

I am wondering if the following can be done 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 am using babel es2015 stage-1, so I could distribute the dictionary as follows:

const extraProps = {[propKey]: 'some value'};
const jsx = <MyComponent {...extraProps} />

but it seems too awkward for one footing. I do not want to use React.createElement; all my classes are es6 classes. Thank!

+4
source share
2 answers

You can create an object in JSX using computed property names and distribute it:

const propKey = 'someProp';
const jsx = <MyComponent { ...{ [propKey]: "some value" } } />;
+5
source

JSX - React.createElement. React.createElement:

const element = React.createElement(MyComponent, {[propKey]: 'some value'});
+3

Source: https://habr.com/ru/post/1666517/


All Articles