I am new to react and trying to have a header component for each page. My header component is loading but the children are not getting loaded.
Index.js
import React from "react";
import {render} from "react-dom";
import {BrowserRouter, Route,Switch} from 'react-router-dom';
import {Root} from "./components/Root";
import {Home} from "./components/Home";
import {User} from "./components/User";
class App extends React.Component {
render(){
return (
<BrowserRouter >
<Switch>
<Route path="/" component={Root} >
<Route path="/user" component={User}/>
<Route path="/home" component={Home}/>
</Route>
</Switch>
</BrowserRouter>
) ;
}
}
render(<App />,window.document.getElementById("app"));
Package.json
{
"name": "react-1",
"version": "1.0.0",
"description": "My first react app",
"main": "index.js",
"scripts": {
"start": "npm run build",
"build": "webpack -d && cp src/index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot --history-api-fallback",
"build-prod": "webpack -p && cp src/index.html dist/index.html"
},
"author": "Saurabh",
"license": "MIT",
"dependencies": {
"babel-core": "^6.26.0",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1"
}
}
Root.js
import React from "react";
import {Header} from "./Header";
export class Root extends React.Component {
render(){
return (
<div className="container">
<div className="row">
<div className="col-xs-10 col-xs-offset-1">
<Header />
</div>
</div>
<div className="row">
<div className="col-xs-10 col-xs-offset-1">
dummy text{this.props.children}
</div>
</div>
</div>
);
}
}
Header.js
import React from "react";
export const Header =(props) => {
return (
<nav className="navbar navbar-default">
<div className="container">
<div className="navbar-header">
<ul className="nav navbar-nav">
<li><a href="#">Home</a></li>
<li><a href="#">User</a></li>
</ul>
</div>
</div>
</nav>
);
};
I can see the dummy text, but when I am trying /user or /home the respective pages are not getting loaded. The page is refreshed.
Nested routes work differently in react-router v4. You should move your nested routes directly into the
Root
componentrender
method.Index.js
Root.js
The
Switch
inIndex.js
will route to theRoot
component which has it's ownSwitch
which will render the firstRoute
that matches the url.