Passing Props (img url ) using React-Modal

Viewed 360

I need to pass image url to modal in react js. Like, on click the item from the "imgae attachment", it shows the modal with image for selected item. But it can't show my image data by passing img={item.document}, Here is my code below:

codesandbox.io/s/distracted-tree-9c0um?file=/src/index.js

DepositRecord.js

import React, { Component } from "react";
import { Table } from "react-bootstrap";
import { Button, ButtonToolbar } from "react-bootstrap";
import { AddDepositModal } from "./AddDepositModal";

export class DepositRecord extends Component {
  constructor(props) {
    super(props);
    this.state = { deps: [], addModalShow: false };
  }

  componentDidMount() {
    this.refershList();
  }

  refershList() {
    this.setState({
      deps: [
        {
          id: 9,
          userId: "12",
          document:
            "https://media.wired.com/photos/5b899992404e112d2df1e94e/master/pass/trash2-01.jpg"
        },
        {
          id: 8,
          userId: "16",
          document:
            "https://techmonitor.ai/wp-content/uploads/sites/20/2016/06/what-is-URL.jpg"
        },
        {
          id: 6,
          userId: "13",
          document:
            "https://images.ctfassets.net/lzny33ho1g45/T5qqQQVznbZaNyxmHybDT/b76e0ff25a495e00647fa9fa6193a3c2/best-url-shorteners-00-hero.png?w=1520&fm=jpg&q=30&fit=thumb&h=760"
        },
        {
          id: 4,
          userId: "1",
          document:
            "https://www.lifewire.com/thmb/l7qM6RfTXYLUUfryFavWEkcT1XY=/3940x2529/filters:no_upscale():max_bytes(150000):strip_icc()/surf-internet-url-henrik5000-e-getty-images-56fa7f855f9b5829867282a9.jpg"
        },
        {
          id: 2,
          userId: "1",
          document:
            "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.dignited.com%2F35306%2Fwhat-makes-up-a-url-uniform-resource-locator%2F&psig=AOvVaw2cW9zGMxysgZ9_QW8Snask&ust=1642150062592000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCKDcgfOrrvUCFQAAAAAdAAAAABAq"
        }
      ]
    });
  }

  //Noted that my orignal array list is fetch method
  //please let me know if there is anychange of my array list, thank you so much!
  //  async refershList() {
  //    const cookies = new Cookies();
  //    await fetch('https://xxxxxxxxxx/xxxx/DepositData', {
  //        headers: { Authorization: `Bearer ${cookies.get('userToken')}` }
  //    })
  //        .then(response => response.json())
  //        .then(data => {
  //            this.setState({ deps: data });
  //        });
  //}

  render() {
    const { deps } = this.state;

    let addModalClose = () => this.setState({ addModalShow: false });

    return (
      <div>
        <h3>Customer's Deposit Record</h3>
        <br />

        <Table className="mt-4" striped bordered hover size="sm">
          <thead>
            <tr>
              <th>Deposit id</th>
              <th>user id</th>
              <th>img attachment</th>
            </tr>
          </thead>
          <tbody>
            {deps.map((item) => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.userId}</td>
                <td>
                  <ButtonToolbar>
                    <Button
                      variant="primary"
                      onClick={() => this.setState({ addModalShow: true })}
                    >
                      image attachment
                    </Button>

                    <AddDepositModal
                      show={this.state.addModalShow}
                      onHide={addModalClose}
                      img={item.document}
                    />
                  </ButtonToolbar>
                </td>
              </tr>
            ))}
          </tbody>
        </Table>
      </div>
    );
  }
}

export default DepositRecord;

AddDepositModal.js <--the Madal component

import React, { Component } from 'react';
import { Modal, Button, Row, Col, Form } from 'react-bootstrap';

export class AddDepositModal extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

            <Modal
                
                {...this.props}
                size="lg"
                aria-labelledby="contained-modal-title-vcenter"
                centered
            >
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-vcenter">
                    Deposit Record
                    </Modal.Title>
                </Modal.Header>
                <Modal.Body>
                <img src={this.props.img} width={700} height={1100}/>
                </Modal.Body>
                <Modal.Footer>
                    <Button variant="danger" onClick={this.props.onHide}>Close</Button>
                </Modal.Footer>
            </Modal>


        );

    }
}
export default AddDepositModal;

My Problem: I am not able to pass the image URL to a Modal component and have no better idea solving it in this code. Noted that my orignal array list is fetch method using Bearer tokens, please let me know if there is anychange of my array list, thank you so much!

Please help me and if any including, changes or complete solution for perfect understanding for the requirement would be really great. Many Thanks in Advance!

1 Answers

You don't have to render as many modals as your items. You can render a single modal and update the content based on the selected item.

Edit magical-panini-5odcm

I've updated the state's structure to group the modal props.

this.state = {
  deps: [],
  modal: {
    show: false,
    img: ""
  }
};

addModalClose = () => this.setState({ modal: { show: false, img: "" } });

<Button
  variant="primary"
  onClick={() =>
    this.setState({
      modal: {
        show: true,
        img: item.document,
      },
    })
  }
>
  image attachment
</Button>;


<AddDepositModal
    show={this.state.modal.show}
    onHide={this.addModalClose}
    img={this.state.modal.img}
/>
Related