Create a new React project using a tool like Create React App:
npx create-react-app my-app
cd my-app
Install React Router:
npm install react-router-dom
Create some components to represent different pages in your application. For example, let's create a Home component and a About component:
import React from 'react';
const Home = () => {
return (
<div>
<h1>Home</h1>
<p>Welcome to the Home page</p>
</div>
);
};
const About = () => {
return (
<div>
<h1>About</h1>
<p>This is the About page</p>
</div>
);
};
Use React Router to define the routes for your application and render the corresponding component based on the current URL:
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const App = () => {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</div>
</Router>
);
};
export default App;
Finally, render the App component in your index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
And that's it! Now you have a basic single page application in React. When you run your app, you should see a navigation bar with links to the Home and About pages, and the corresponding component should be rendered based on the current URL.
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter