I am creating a whatsapp clone.
For showing profile picture, I have made a card component which is accessed from a top_bar component.
function Show_dp(prop){
return(
<div id="box">
<div id="dp">
<img src={prop.image}></img>
</div>
<div id="buttons">
<div className="buttons_dp">
<FontAwesomeIcon className="ico" fontSize="1.5em" color="white" icon={faMessage} />
</div>
</div>
)
}
export default Show_dp;
The top_bar component is as follows:
function Top_bar(prop){
const [dp, setdp] = useState(false);
function toggle_dp(){
setdp(!dp);
console.log(dp);
}
return(
<>
<div id="bar_container">
<div id="bar_left">
<FontAwesomeIcon fontSize="1.2em" color="#ebebeb" icon={faArrowLeftLong} className="icon"/>
{/* <FontAwesomeIcon fontSize="1.5em" color="#ebebeb" icon={faUserCircle} className="icon"/> */}
<div id="profile_picture" onClick={toggle_dp}>
<img src={prop.image}></img>
</div>
</div>
<div id="bar_middle">{prop.name}</div>
<div id="bar_right">
<FontAwesomeIcon fontSize="1.1em" color="#ebebeb" icon={faVideoCamera} className="icon"/>
<FontAwesomeIcon fontSize="1.1em" color="#ebebeb" icon={faPhone} className="icon"/>
<FontAwesomeIcon fontSize="1.1em" color="#ebebeb" icon={faCog} className="icon"/>
</div>
</div>
<div id="dp_card" style={{display: dp? "flex": "none"}}>
<Show_dp image = {profile_picture} />
</div>
</>
)
}
export default Top_bar;
In this, top_bar component, whenever I will click on the profile_picture div, it will show the dp_card component.
Now, when the dp_card component is showing, I want to make the buttons_dp buttons of the dp_card do something inside the top_bar component (i.e. hide the dp_card onClick).
So, I want to access the onClick button of a Show_dp component from the Top_bar component.
How can I do the same? Please help me learn a new thing!
In the above image (showing the dp_card component), I want to access the message button (left_most) which will help remove the dp_card (i.e. set display of dp_card to "none").
I am facing trouble with using a onClick button of one component inside another component.
2
Answers
To allow the Top_bar component to control the behavior of the buttons inside the Show_dp component, you can lift the state up and pass down functions via props.
In React it is called
Lifting State Up
you can read more about it here.https://react.dev/learn/sharing-state-between-components
Show_dp
ComponentTop_bar
Component:In the Top_bar component, send dp and setdp method along with profile_picture, this will allow you to use the setdp function in the Show_dp component:
Make changes in Top_bar here:
You can do something like this in Show_dp component: