I am a beginner in React so please be patient with me ))
I have a parent component with two different buttons that trigger a child component which is a Modal that must show different data inside it depending on which button has triggered the Modal. Both components are functional components. The child Modal is supposed to receive the triggering button’s value via props from the parent. That name is a single letter that I use to construct an object’s name that gets the modal’s data from two constants defined within the Modal.
When I try to console.log the button’s name received via the props, I get an “undefined” error in the console. Consequently, I cannot construct the Modal’s contents due to that.
I prefer to define my components as functions rather that extending a class.
Is there something I am doing wrong in my code?
Parent component (Experience.jsx):
import React, { useState } from "react"; import Container from 'react-bootstrap/Container'; import Col from 'react-bootstrap/Col'; import Button from 'react-bootstrap/Button'; import ExperienceModal from "./ExperienceModal"; function Experience() { const [modalShow, setModalShow] = React.useState({ value: false, bname: "" }); function defineModal(event) { setModalShow({value: true, bname: event.target.value}) } return ( <Container fluid> <Col><Button value="F" onClick={defineModal}>More Information</Button>{''}</Col> <Col><Button value="E" onClick={defineModal}>More Information</Button>{''}</Col> <ExperienceModal show={modalShow.value} onHide={() => setModalShow({value: false, bname: ""})} mshow={modalShow} /> </Container> export default Experience;
Child component (ExperienceModal.jsx):
import React from "react"; import Modal from 'react-bootstrap/Modal'; import Button from 'react-bootstrap/Button'; function ExperienceModal(props) { var x = props.mshow.bname; console.log(x); const F = { inf1: "test test test", inf2: "text text text", inf3: "words words words" } const E = { inf1: "sample text sample text", inf2: "this is just a sample text", inf3: "another sample text" } return ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter"> Additional Information </Modal.Title> </Modal.Header> <Modal.Body> <h4>Centered Modal</h4> <p>{x.inf1}</p> <p>{x.inf2}</p> <p>{x.inf3}</p> </Modal.Body> <Modal.Footer> <Button onClick={props.onHide} variant="success">Close</Button> </Modal.Footer> </Modal> ); } export default ExperienceModal;
Advertisement
Answer
setModalShow(value = true, bname = event.value)
should be setModalShow({value: true, name: event.value})
props are undefined because setModalShow should recive new state value, but expression (value = true) evaluates to undefined