React - map array to child component React - map array to child component arrays arrays

React - map array to child component


Your info object is not an iterable list - so I would convert them into a list {title, text} like so:

const data = info.title.map((e,i) => {  return {title : e, text: info.text[i]}})

Now I would shift the map() function to ComponentA instead of Child as that makes the child component more meaningful.

See demo below:

const info = {  title: ["Title1", "Title2"],  text: ["Paragraph1", "Paragraph2"]};const data = info.title.map((e,i) => {  return {title : e, text: info.text[i]}})const ComponentA = () => {  return (    <div>      <h1>Home Page</h1>      { data.map(item => {          return (            <Child key={item.title} title={item.title} text={item.text} />          );        })      }    </div>  )}const Child = ({ text, title }) => {  return (    <div>      <h3>{title}</h3>      <p>{text}</p>    </div>  );};ReactDOM.render(  <ComponentA/>,   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"/>


You can change your children component like this, since text is an array so you need to access it values by index.

const Child = ({ text, title }) => {  return (    <div>      {text.map((text,index) => {        return (          <div>            <h3>{title[index]}</h3>            <p>{text}</p>          </div>        );      })}    </div>  );};

You can even change you parent component to something like this

import Child from "../components/child";const ComponentA = () => {  <Layout>    <h1>Home Page</h1>    {info.text.map((text,index)=> <Child title={info.title[index]} text={text} />}  </Layout>}const info = {  title: ["Title1", "Title2"],  text: ["Paragraph1", "Paragraph2"]};

And then your child should be

const Child = ({ text, title }) => {  return (    <div>          <h3>{title}</h3>          <p>{text}</p>    </div>  );};


You can iterate over text and usnig index access the title

const ComponentA = () => {  return (    <div>      <h1>Home Page</h1>      <Child title={info.title} text={info.text} />    </div>  )}const info = {  title: ["Title1", "Title2"],  text: ["Paragraph1", "Paragraph2"]};const Child = ({ text, title }) => {  return (    <div>      {text.map((text1, index) => {        return (          <div>            <h3>{title[index]}</h3>            <p>{text1}</p>          </div>        );      })}    </div>  );};ReactDOM.render(<ComponentA />, document.getElementById('app'));
<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="app"/>