Create ReactJS Project
Create new folder named LearnReactJSWithRealApps and select to this folder in Visual Studio Code
Open Terminal windows in Visual Studio Code and use commands below:
npm install create-react-app@latest
npx create-react-app myapp
npm install react-router-dom
Create New Component
Open App.js file in src folder and create new component as below:
import React from 'react';
import { BrowserRouter, Link, Switch, Route } from 'react-router-dom';
let App = () => {
var paddingLeft = { paddingLeft: '10px' };
return (
<BrowserRouter>
<Link to="/menu1">Menu 1</Link>
<Link to="/menu2/p01" style={paddingLeft}>Menu 2</Link>
<Link to="/menu3/p02/456" style={paddingLeft}>Menu 3</Link>
<br /><br />
<Switch>
<Route exact path="/" component={Menu1} />
<Route path="/menu1" component={Menu1} />
<Route path="/menu2/:id" component={Menu2} />
<Route path="/menu3/:id1/:id2" component={Menu3} />
</Switch>
<br /><br />
Copyright PMK Lab
</BrowserRouter>
);
};
let Menu1 = () => {
return (
<h3>Menu 1</h3>
);
};
let Menu2 = (props) => {
const { id } = props.match.params
return (
<div>
<h3>Menu 2</h3>
id: {id}
</div>
);
};
let Menu3 = (props) => {
const { id1, id2 } = props.match.params
return (
<div>
<h3>Menu 3</h3>
id1: {id1}
<br />
id2: {id2}
</div>
);
};
export default App;
Add Component to Entry File
Open index.js file in src folder and add new component to this file as below:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
Structure of Project
Run Application
In Terminal windows in Visual Studio Code and type: npm start,
program will open url http://localhost:3000 on browser
Output
Click Menu 1 link to call Menu1 component with url: http://localhost:3000/menu1
Click Menu 2 link to call Menu2 component with url: http://localhost:3000/menu2/p01
Click Menu 3 link to call Menu3 component with url: http://localhost:3000/menu3/p02/456