2

I have a div element in which I want to show one item on a click of a button. But every time a user clicks a button, I want him to be able to add another item, and another, etc. Making it a list.

How do I accomplish this with React?

I know I have to separate an item, right?

const Item = () => (
  <div>
    <h1>Hello</h1>
  </div>
)

And then? I'm assuming it's not the same as simply showing/hiding a div with ternary operators? Because the button needs to add +1 every time someone clicks it. Or am I wrong?

Can someone please point me in the right direction because I'm not sure how to search this? Thank you!

1 Answer 1

3

Simply put store your item data to state, then use map on that state e.g.

If you use hooks for state.

{items && items.map(item => <Item someProp={item.someValue} />)}

If you have a class based component.

{this.state.items && this.state.items.map(item => <Item someProp={item.someValue} />)}

Note the && is there so react doesn't try to map over a empty state and only maps if the value is truthy aka in this case the state has something in it, if you would try to map over a empty state it would crash react.

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

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.