I have some React Components:
- Row component, here is the snippets:
export default Row() {
return (
<>
<div className="grid grid-4-cols">
// Here is the cell details
...
// Code below are one of the cell
<div>
<button id="show-modal" type="button" onclick={showModal}></button>
<div>
...
<div>
</>
);
}
- Modal component
export default Modal() {
return (
// Below are elements in the modal
<div>
...
</div>
);
}
- Table component
import Row from "./Row";
import Modal from "./Modal";
export default function Table {
// I am trying to use React Hook
const [modalOn, setModalOn] = useState(false);
return (
<>
<div>
// Some table features
<Row/>
<Row/>
</div>
{modalOn && <Modal/>}
</>
)
}
I want to implement so that when show-modal button being clicked, the modalOn are set to true. Where to implement this showModal function?
CodePudding user response:
So, you need to declare the showModal function in the Table component, which will change modalOn state to true, and pass it as prop to the Row components.
Row component
export default Row({ showModal }) {
return (
<>
<div className="grid grid-4-cols">
// Here is the cell details
...
// Code below are one of the cell
<div>
<button id="show-modal" type="button" onclick={showModal}></button>
<div>
...
<div>
</>
);
}
Modal component
export default Modal() {
return (
// Below are elements in the modal
<div className="hidden">
...
</div>
);
}
Table component
import Row from "./Row";
import Modal from "./Modal";
export default function Table {
// I am trying to use React Hook
const [modalOn, setModalOn] = useState(false);
const showModal = () => {
setModalOn(true)
}
return (
<>
<div>
// Some table features
<Row showModal={showModal}/>
<Row showModal={showModal} />
</div>
{modalOn || <Modal/>}
</>
)
}
CodePudding user response:
Ideally As per React it is recommended to lift up the state as & when possible so acc to me your should keep separate component as model component.. & you pass props to open close to this component..
Also you can make this modal reusable if u are willing to accept content as a children.
