i am trying to build app which is searching Movies database api. I have main fetch function in App.js. In tutorials people using searchbar in this main APP component. Isnt better to use separate Navbar component witch searchbar and then pass that value to the main App where is fetch fuction and change that function based on searched value? is there any way to pass that input value without Redux ? I googled "lifting state up" but i am little bit confused.:) Thank You Main App.js
const [movies, setMovies] = React.useState([]);
const example = [1, 2, 3];
React.useEffect(() => {
console.log("hehe");
fetch(
"https://api.themoviedb.org/3/trending/all/week?api_key=564564564"
)
.then((res) => res.json())
.then((data) => {
console.log(data);
setMovies(data.results);
});
}, []);
return (
<div>
<Navbar />
<div className="container1">
<div className="movie">
{movies.map((movieReq) => (
<Movieinfo key={movieReq.id} {...movieReq} />
))}
</div>
</div>
</div>
);
}
export default App;
Here is Navbar with searchbar and input value which i want to pass to App.js
import "./Navbar.css";
function Navbar() {
return (
<div>
<nav class="navbar navbar-light bg-light">
<a class="navbar-brand">Navbar</a>
<form class="form-inline">
<input
class="form-control mr-sm-2"
type="search"
placeholder="Search"
aria-label="Search"
/>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">
Search
</button>
</form>
</nav>
</div>
);
}
export default Navbar;
There are two simple ways you can solve your problem.
You can put all your login in app.js and create two other components, main.js, and nav.js. You can pass the state as props to both components.
function App() {
const [movies, setMovies] = useState([]);
const [search, setSearch] = useState([]);
return (
<>
<Main movies={movies} setMovies={setMovies}/>
<Navbar search={search} setSearch={setSearch} />
</>
)
}
function Main({movies, setMovie}) {
return (
<>
// you can render here
</>
)
}
function Main({search, setSearch}) {
return (
<>
// change the search here
</>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>