'How to target props of a component already nested inside another component
I am trying to render a different component in my App.js based on an OnClick placed in a button nested inside my Home component. Essentially I want the Home component to initially be rendered and then my "Restaurants" component to replace it when I click on the "Explore Restaurants" (which changes the state from true to false) button which is nested in my Home component. I am new to react so I'm sure there is an easy way to do this but I'm feeling a bit lost.
Here is the code
**App.js:**
import React, {useState} from "react";
import './App.css';
import Home from "./home"
import Footer from "./footer"
import Header from "./header"
import Resturants from "./resturants";
function App() {
var [count, setCount] = useState(false);
return (
<div>
<Header/>
{count ? <Home /> : <Resturants/> }
<Footer/>
</div>
);
}
export default App;
**Home.js**
import React, {useState} from "react";
import Button from "./button";
import {Stack} from "react-bootstrap";
import Promotions from './promotions'
//This component purely renders the home page when the user opens the app.
function Home (){
function changePage (){
setCount(count = true)
}
return (
<Stack>
<Promotions />
<Button className ="homeButtons" buttonText="Login" />
<Button className ="homeButtons" buttonText="Signup" />
<Button onClick ={changePage} className ="homeButtons" buttonText="Explore Resturants" />
</Stack>
)
}
export default Home
**Button.js**
import React from "react"
function Button (props){
return (<button onClick={props.onClick} style={props.style} className ={props.className} type = {props.type}> {props.buttonText} </button>
)
}
export default Button
Solution 1:[1]
You should pass the setCount
method down to the Home
component as a prop:
function App() {
var [count, setCount] = useState(false);
return (
<div>
<Header />
{count ? <Home setCount={setCount} /> : <Resturants />}
<Footer />
</div>
);
}
And then, retrieve it in the Home
component:
function Home({ setCount }) {
function changePage() {
setCount((oldCount) => !oldCount);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lpizzinidev |