Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dynamic prop name in React?

Tags:

reactjs

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.

like image 970
JoeTidee Avatar asked Nov 29 '16 14:11

JoeTidee


People also ask

Can I rename props in React?

Press F2 and then type the new desired name and press Enter. All usages of the symbol will be renamed, across files.

What is Componentref in React?

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components.


1 Answers

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 Object.keys on props to get all dynamic prop names.

Edit: Added an example

class Test extends React.Component {        renderFromProps() {      return Object.keys(this.props)      .map((propKey) =>        <h3>{this.props[propKey]}</h3>      );    }    render() {      return (       <div>        <h1>One way </h1>        <hr/>        <h3>{this.props.name}</h3>        <h3>{this.props.type}</h3>        <h3>{this.props.value}</h3>        <hr/>       <h1> Another way </h1>        <hr/>        { this.renderFromProps()}       </div>     );    }      }    const dynamicProps = { name:"Test", type:"String", value:"Hi" };    ReactDOM.render(    <Test {...dynamicProps} />,    document.getElementById('root')  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>  <div id="root">  </div>
like image 193
WitVault Avatar answered Sep 23 '22 18:09

WitVault