Home > OS >  Passing data to modal with React component
Passing data to modal with React component

Time:08-10

I'm creating a list of projects clickable, that when it's clicked show the project in a modal with more details.

I created a component like this:

const Projects = (props) => {

    const [modalOn, setModalOn] = useState(false);

    const handleOnOpen = () => setModalOn(true);
    const handleOnClose = () => setModalOn(false);

    return (
        <div id="projects">
            <ul key="1">
                {
                    props.children.map((data, index) => {
                        return <li key={data.id} className="mx-2 rounded-lg border">
                            <div className="overflow-hidden cursor-pointer" onClick={ () => handleOnOpen }>
                                <CoverRender>{data}</CoverRender>
                            </div>
                            <div className="px-4 pt-3">
                                <h1 className="font-bold">{data.name}</h1>
                                <p>{data.description}</p>
                            </div>
                        </li>
                    })
                }
            </ul>
            <Modal onClose={handleOnClose} visible={modalOn} projectModalData={modalData}/>
        </div>
    );
};

export default Projects;

notice that the 'props' data source is a simple array that iterates over each project rendering a list, and that the Modal component is called at the end, after the iteration, how can I link a project from the list with the corresponding information in the modal?

I've already tried to add an option in onClick to pass the date value to ModalData, but when I click this variable it has no value.

CodePudding user response:

add state for your data and call setModalData when you click on item, then pass modalData as prop to your modal

const [modalData, setModalData] = useState(null);
  • Related