Toggle one component from another using React hook
I have a two child components and I want a button in one of them to toggle (on/off) the html in another. I have watched tutorials on lifting state up, and communication between components but most of it has to do with moving data. I want to manipulate a component from another. I would like the achieve this using useState, and without useContext if possible. Thanks!
THE PARENT
import React from "react";
function App() {
return (
<div>
<AppProvider>
<ComponentOne/>
<Slideshow />
<ComponentTwo/ >
</AppProvider>
</div>
);
}
CHILD 1
export default function ComponentOne() {
return (
<div>
<button>The button that toggles</button>
</div>
);
}
CHILD 2
export default function ComponentTwo() {
return (
<div>
<div>The content that hides/shows</div>
</div>
);
}
Solution 1:
You need to use state
to toggle the values. Pass the state to the ComponentTwo
as props and pass the state updater function as the callback function to the ComponentOne
as a prop.
import React , { useState, useCallback } from 'react';
function ComponentOne({ onToggle}) {
return (
<div>
<button onClick={onToggle}>The button that toggles</button>
</div>
);
}
function ComponentTwo({show}) {
return (
<div>
{show && <div>The content that hides/shows</div>}
</div>
);
}
export default function App() {
const [show, setShow ] = useState(true);
const handleToggle = useCallback(() => setShow(prevShow => !prevShow),[])
return (
<div className="App">
<ComponentOne onToggle={handleToggle} />
<ComponentTwo show={show} />
</div>
);
}
Refer
useState
useCallback