0

I have the following array:

const elements = [
    {
        title: "foo"
        section: <div>Foo <button onClick={sayHello}>Greet</button></div>
    },
    {
        title: "bar"
        section: <div>Bar <button onClick={sayHello}>Greet</button></div>
    }
];

I want to render the component with something like:

const someSections = this.state.elements.map((item, i) => (
    <div key={i}>
    {item.section}
    </div>
));

...

render(){
    return (
        ...
        <div>
            {someSections}
        </div>
    )
}

But I can't render them. The error is:

Uncaught Error: objects are not valid as a React child

2
  • item.section, not link.section in your map :D Commented Feb 24, 2017 at 14:15
  • Your data really shouldn't contain HTML, only the templates Commented Feb 24, 2017 at 14:25

2 Answers 2

1

Check the working solution:

const data = [
    {
        title: "foo",
        section: <div>Foo <button>Greet</button></div>
    },
    {
        title: "bar",
        section: <div>Bar <button>Greet</button></div>
    }
]


class App extends React.Component{
  render(){
     return(
        <div>
          {
              data.map((item,i)=>{
                  return <div key={i}>{item.section}</div>
              })
          }
        </div>
     )
  }
}

ReactDOM.render(
    <App/>,
    document.getElementById('app')
);
<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='app'></div>

Sign up to request clarification or add additional context in comments.

Comments

1

normally you would do something like this.

render(){
    let someSections = this.state.elements.map((item, i) => (
        <div key={i}>
            {item.section}
        </div>
    ));

    return (
        <div>
            {someSections}
        </div>
    )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.