I am trying to pass value of the element clicked to the header component. I did that with modal provided by React-bootstrap.
The parent component (header) should receive the value of the element clicked (in child) and display in location (state). I have taken too much time on this already.
import React, {useState} from 'react'
import { Navbar, Container, Button } from 'react-bootstrap'
import {
faMapMarkerAlt,
faAngleDown
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import LocationModal from '../LocationModal/LocationModal';
export default function Header () {
const [modalShow, setModalShow] = useState(false)
const [location, setLocation] = useState('Lagos')
const handleCallback = () => {
setLocation({location})
}
return (
<>
<Navbar expand="lg" variant="light" bg="light">
<Container>
<Navbar.Brand href="/">Navbar</Navbar.Brand>
<Button variant="none" onClick={() => setModalShow(true)} className="px-2 d-inline-flex">
<span className="ml-1"><FontAwesomeIcon icon={faMapMarkerAlt} /></span>
<span className="ml-1">{location}</span>
<span className="ml-1"><FontAwesomeIcon icon={faAngleDown} /></span>
</Button>
</Container>
</Navbar>
<LocationModal
show={modalShow}
onHide={() => setModalShow(false)}
parentcallback={handleCallback}
/>
</>
)
}
Location Modal
As you can see, I tried to write a callback function for the value obtained from child element (locationModal) so that it can be passed on and display in parent component (Header).
import React from 'react'
import { Modal } from 'react-bootstrap'
export default function LocationModal(props) {
const locations = [
{
id: 1,
location: 'Lagos'
},
{
id: 2,
location: 'Abuja'
}
]
const handleClick = (value) => {
props.parentcallback(value)
}
return (
<Modal
{...props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton className="border-bottom-0">
<Modal.Title id="contained-modal-title-vcenter"></Modal.Title>
</Modal.Header>
<Modal.Body>
<ul className="d-flex flex-column align-items-center list-unstyled">
<h1>Choose Your Location</h1>
{
locations.map(item => {
return <li
className="w-75 p-2 m-2 border-1 text-white text-center bg-gray-300 cursor-pointer"
key={item.id}
onClick={() => handleClick(item.location)}
value={item.location}
>
{item.location}
</li>
})
}
</ul>
</Modal.Body>
</Modal>
);
}
Thank you so much.
question from:
https://stackoverflow.com/questions/65853370/how-to-pass-data-from-child-to-parent-when-a-list-item-is-clicked 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…