Reputation: 3444
I am trying to activate a Modal window from a button that is in the parent component, but I cannot make it work. Its a react-bootstrap modal if it matters. When the button that activates the modal is clicked, I get an error that says that the Numpad is undefined and can't access toggle() of undefined. I have tried to do this with useRef():
function App() {
const NumpadRef = useRef();
// When I click the button Here I get that NumpadRef is undefined and cant access toggle();
const OpenNumpad = () => { NumpadRef.current.toggle() };
return (
<>
<Numpad ref={NumpadRef}></Numpad>
<button onClick={OpenNumpad}>Open Numpad</button>
</>
);
}
And the Numpad:
function Numpad() {
[show, setShow] = useState(false);
const toggle = () => { setShow(!show) };
return (
<Modal show={show} onHide={toggle}>....</Modal>
);
}
Edit: I am aware of the "lift the state up" approach, but doing that and activating the modal will cause the whole App component to re-render and I have a ton of other components within it. Is there a way to do this without lifting the state?
Upvotes: 2
Views: 1267
Reputation: 3444
I have solved this by extracting the state of the numpad into a context that way I can activate it from any button and send any data I want to it.
Upvotes: 0
Reputation: 269
The ref.current
is giving you a ref to the html element not the react element and in your case you are trying to invoke react method.
The solution is to 'Raise' the state up. That means that the numpad component won't own the state and the events that changes it but the app will.
function App() {
[show, setShow] = useState(false);
const handelNumpadToggle = () => { setShow(!show) };
return (
<>
<Numpad show handelTugge={handelNumpadToggle}l></Numpad>
<button onClick={handelNumpadToggle}>Open Numpad</button>
</>
);
}
function Numpad(show , handelTuggel) {
return (
<Modal show={show} onHide={handelTuggel}>....</Modal>
);
}
Upvotes: 1