简体   繁体   中英

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>
    )
  }
}

add check if parentId is equal to item.parentId :

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM