Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Prop Key Dynamically JSX

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!

like image 377
treyhakanson Avatar asked Feb 05 '23 08:02

treyhakanson


2 Answers

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" } } />;
like image 68
Ori Drori Avatar answered Feb 08 '23 10:02

Ori Drori


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'});
like image 25
Felix Kling Avatar answered Feb 08 '23 12:02

Felix Kling