Send props to another functional component on click

I just learned react and I am building a simple blog app in react and I am trying to send props on button click But the props is not showing in the another functional component.

I am using react-bootstrap for modal (which is second component). And I am using for edit the current blog when user click on edit button in first component.

App.js

function SecondModalComponent(props) {

    return (
    <>
      <Modal show={props.show}>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>
            
            <input type="text" value={props.title} />

        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={props.onHide}>
            Close
          </Button>
        </Modal.Footer>
      </Modal>

    </>
    )
}

const response = [
    {
        title: "First Blog",
        description: "First Blog"
    },
    {
        title: "Second Blog",
        description: "First Blog"
    },
    {
        title: "Third Blog",
        description: "First Blog"
    }
]

function BlogFirstComponent() {
    const [show, setShow] = useState(false);

    const openEditModal = (title) => {
        <SecondModalComponent 
            title={title}
        />
    }

    return (
    <>

      <SecondModalComponent
        show={modalShow}
        onHide={() => setShow(false)}
      />


        {
           response.map((data) => 
           <div>
                <b>Title</b> {data.title}
                <b>Title</b> {data.description}

                <span onClick={() => openEditModal(data.title)}>Edit</span>
           </div>
         )}
    </>
    )
}

I have tried many times but it is still no showing the prop title.

Any help would be much Appreciated.

>Solution :

this is not how react model works with UI component, component should be declarative, and not returned on a callback on click handler.

you can define your modal at the top level of your component

function BlogFirstComponent() {
    
    const [secondModalOpen, setSecondModalOpen] = useState(false);
    const [data, setData] = useState({ title: '', description: '' });

    return (
    <>

         <SecondModalComponent 
          {...data}
          show={secondModalOpen}
          onHide={() => setSecondModalOpen(false)}
        />

        ...
        {
           response.map((data) => 
           <div>
                <b>Title</b> {data.title}
                <b>Title</b> {data.description}

                <span onClick={() => {
                  setData({...data}); 
                  setSecondModalOpen(true);
                }>Edit</span>
           </div>
         )}
    <>
   );
}

Now, whenever someone clicks the button, the modal is opened, and the right props are passed to the component at that moment.

Leave a Reply