How to render a modal on a map using React?

Asked

Viewed 127 times

-1

I have an application in React that searches products of an api, I want to render a table where each item has a button that opens the modal and updates (sends a PUT in the API) the product. Only the modal is always receiving the id 1, as if it did not receive the others.

Follows the code:

import ModalUpdate from './ModalUpdate';

const [showModalUpdate, setShowModalUpdate] = useState(false);

<TableBody>
    {products.map(item => (
      <TableRow key={item.id}>
        <TableCell>{item.name}</TableCell>
        <TableCell>{item.points}</TableCell>
        <TableCell>
            <Button onClick={()=>{openModalUpdate()}}>
                Atualizar
            </Button>
            {showModalUpdate ? (
                <ModalUpdate
                    open={showModalUpdate}
                    id={item.id}             
                    onClose={closeModalUpdate}
                />
          ) : null}
        </TableCell>
      </TableRow>
</TableBody>
  • I think the problem is in the state, which is shared for all Modal. It has to have a status for each Modal.

1 answer

-1

Try creating a function to select the product

activeProduct(product, index) {
    this.setState({
        current: product,
        currentIndex: index
    })
}

After render here is in list format, you will need to change to your table

render()
 const { product, currentProduct, currentIndex } = this.state

    <ul className="list-group">
                            {products && products.map((product, index) => (
                                <li 
                                    className={"list-group-item " + (index === currentIndex ? "active" : "")} 
                                    onClick={() => this.activeProduct(product, index)} 
                                    key={index} >
                                        {product.name}
                                </li>
                            )) }
                        </ul>
    <div className="col-md-6">
      {currentMembro ? (
         {currentProduct.name}
         {currentProduct.points} )
    </div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.