In react, There is one component A inside there is one component B I have used. There is one more component C, and inside C there is one button which is when clicked it hides the component B from component A. How can I achieve this functionality
CodePudding user response:
Using only React, you can achieve this by:
- Parent/root component to all of these components has a boolean state, let's call it
showComponentB
. It's initialized totrue
. - This root component passes down the state
showComponentB
as a prop to Component A. In Component A, it is used to either show Component B ifshowComponentB
istrue
or hide if it'sfalse
. - Root component passes a function to alter the state of
showComponentB
into Component C and is called when the button is clicked. - State of
showComponentB
is updated in root tofalse
and that updated value is passed through to Component A and hides Component B.
CodePudding user response:
You can try something like this. Hope it helps you.
import { useState } from "react";
import "./styles.css";
export default function App() {
const [isVisible, setIsVisible] = useState(true)
return (
<div className="App">
<CompA>
{isVisible && <CompB>
<CompC clickHandler={()=>setIsVisible(false)}/>
</CompB> }
</CompA>
</div>
);
}
export const CompA = (props) => {
return <>
<div style={{backgroundColor:'red', height:'200px',width:'200px'}}>Component A
{props.children}
</div>
</>}
export const CompB = (props) => {
return <>
<div style={{backgroundColor:'blue', height:'150px',width:'150px'}}>Component B
{props.children}
</div>
</>
}
export const CompC = (props) => {
return <>
<div style={{backgroundColor:'green', height:'100px',width:'100px'}}>Component C
<button onClick={props.clickHandler}>hide B</button>
</div>
</>
}