this is my first question here and I apologize upfront if it already been answered. I’m studying react and I started a project as well, and my question is: how can I make my App component a home page? Or do I have to create a component to do so? I´m using react-router-dom for navigation, like the code below, and keep getting the message “No routes matched location “/””. How can I set a route to it? I would like to use the App component instead of using a page component named home. If I did something wrong about the post, again, I’m sorry. Thanks in advance.
import React from 'react' import {BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom' import Blog from './pages/Blog' import About from './pages/About' import Faq from './pages/Faq' import Market from './pages/Market' import GlobalStyle from './styles/global' function App() { return ( <Router> <GlobalStyle/> <header> <nav> <Link to="/products">Nosso produtos</Link> <Link to="/blog">Diário do Café</Link> <Link to="/faq">Cafaq - perguntas frequentes</Link> <Link to="/about">Sobre nós</Link> </nav> </header> <Routes> <Route path="/products" element={<Market />} /> <Route path="/blog" element={<Blog />} /> <Route path="/faq" element={<Faq />} /> <Route path="/about" element={<About />} /> </Routes> <footer> Footer </footer> </Router> ) } export default App
Advertisement
Answer
The App component is already your default component. Any path will render the App component as long as you have wrapped the App component with the BrowserRouter component
// In index.js import App from "./App"; import { BrowserRouter } from "react-router-dom"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <BrowserRouter> <App /> </BrowserRouter> );
so I assume your point is to keep the navbar visible regardless of the current path and that is already done because anything placed in the App component will be rendered, and the paths content will be changed based on the elements specified in the Routes.
In case, you want to create a separate Home component, then you will create a Route with a path ‘/’ and the Home Component element.
Make sure that you understand how routing works to avoid any bugs in the future
Hope you found it helpful.