itgirl1234
itgirl1234

Reputation: 749

Render component inside .map onClick() - React

I'm trying to render component onClick and the problem I faced is that my onClick opens component in every row not only in the one I clicked button. It's probably any index issue. Could you take a look at my code? Thanks!

 class ItemView extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isFormOpen: false,
      parentId: null,
    }
  }

  handleAddItem = (value) => {
    this.setState({
      parentId: value.parentId,
      isFormOpen: !this.state.isFormOpen,
    })
  }

  render() {
    return (
      <div className="ui relaxed divided list">
        {data.items.map((item, index) => {
          return (
            <div className="item" key={index}>
              <Button
                label={'Add Item'}
                onClick={() => this.handleAddItem({ parentId: item.parentId })}
              />
              {isFormOpen && (
                <AddItem parentId={parentId} />
              )}
            </div>
          )
        })}
      </div>
    )
  }
}

Upvotes: 1

Views: 774

Answers (2)

M Shafique
M Shafique

Reputation: 816

You are right. For this you have to use Other Component. In this component because you are using map to render the element so it renders it in every time or row. That's why when isFormOpen will be true so it'll be true on all items/rows.

Please use other component to render the conditional element.

Upvotes: 2

Igor Alemasow
Igor Alemasow

Reputation: 4889

add check if parentId is equal to item.parentId:

{isFormOpen && parentId === item.parentId && (
    <AddItem parentId={parentId} />
)}

Upvotes: 2

Related Questions