hello I'm currently learning about React, and I'm confused about how to pass data or state to another component
i have Search Component like this
function Search(props) {
const [ query, setQuery ] = useState("")
const [ movie, setMovie ] = useState({})
function searchHandler() {
axios.get(`${api.url}SearchMovie/${api.key}/${query}`)
.then(res => {
setMovie(res.data.results)
}).catch(err => {
console.log(err)
})
}
return (
<div className="search-input">
<div class="input-group input-custom mb-3">
<input
type="text"
class="form-control"
placeholder="Search Movie"
onChange={e => setQuery(e.target.value)}
value={query}
/>
<button
class="btn btn-outline-primary"
onClick={searchHandler}
>
Search
</button>
</div>
</div>
);
}
export default Search;
and also MainPage Component like this
function MainPage() {
return (
<div>
<Navbar />
<div className="container">
<Search />
<hr />
<div className="content">
<div className="row">
<div className="col-4">
<Card
image="https://dbkpop.com/wp-content/uploads/2020/06/weeekly_we_are_teaser_2_monday.jpg"
title="Monday"
description="Monday Weeekly Member"
/>
</div>
<div className="col-4">
<Card
image="https://dbkpop.com/wp-content/uploads/2020/06/weeekly_we_are_teaser_2_monday.jpg"
title="Monday"
description="Monday Weeekly Member"
/>
</div>
<div className="col-4">
<Card
image="https://dbkpop.com/wp-content/uploads/2020/06/weeekly_we_are_teaser_2_monday.jpg"
title="Monday"
description="Monday Weeekly Member"
/>
</div>
</div>
</div>
</div>
</div>
);
}
export default MainPage;
the problem is, how to pass State (movie) from Search Component to MainPage Component. so that I can render the data to MainPage Component
Data in React flows down, so you need to lift the state up.
Hence, the movie
state should be in scope of MainPage
:
function MainPage() {
const [ movie, setMovie ] = useState({})
// Set query results with setMovie
return <Search setMovie={setMovie} ... />
}
function Search(props) {
function searchHandler() {
axios.get(`${api.url}SearchMovie/${api.key}/${query}`)
.then(res => {
props.setMovie(res.data.results)
}).catch(err => {
console.log(err)
})
}
return (...);
}
export default Search;