Search code examples
reactjsreact-hookscreate-react-appreact-propsreact-functional-component

How to create a dynamic prop name in react using functional components


This post has the answer I'm looking for but they are using outdated class based components and I need help translating them to functional. How to create a dynamic prop name in React?. How would this post be written if answered using react functional components. Thank you for your time.


Solution

  • function Test(props) {
      const renderFromProps = () => {
        return Object.keys(props)
        .map((propKey) =>
          <h3>{props[propKey]}</h3>
        );
      };
      
      return (
       <div>
        <h1>One way </h1>
        <hr/>
        <h3>{props.name}</h3>
        <h3>{props.type}</h3>
        <h3>{props.value}</h3>
        <hr/>
        <h1> Another way </h1>
        <hr/>
        { 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/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root">
    </div>