reactjsHow do I set up routing in a React.js application?
To set up routing in a React.js application you need to install the react-router-dom package. You can do this by running npm install react-router-dom in your terminal.
Once installed, you need to import the BrowserRouter component from the react-router-dom package and wrap your main App component with it.
import { BrowserRouter } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
{/* App components here */}
</BrowserRouter>
);
}
After this, you can create Route components inside the BrowserRouter component. These Route components will take two props: path and component. The path prop will be a string that specifies the path for the route, and the component prop will be the component that will be rendered when the route matches.
import { BrowserRouter, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<BrowserRouter>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</BrowserRouter>
);
}
Finally, you can use the Link component from the react-router-dom package to create links that will navigate to the different routes.
import { BrowserRouter, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<BrowserRouter>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</BrowserRouter>
);
}
For more information on setting up routing in React, see the React Router documentation.
More of Reactjs
- How can I convert an XLSX file to JSON using ReactJS?
- How can I use ReactJS and ZeroMQ together to create a distributed application?
- How do I create a zip file using ReactJS?
- How do I zip multiple files using ReactJS?
- How do I install Yarn for React.js?
- How can I use Yup with ReactJS?
- How do I use Yup validation with ReactJS?
- How can I use MobX with ReactJS?
- How can I use ReactJS and SASS together?
- How do I implement a year picker using ReactJS?
See more codes...