I'm trying to render a sidebar along with a main content area using react-router-dom
. I could just render <Sidebar/>
normally but I want to pass it the location prop because of another error I was getting where clicking a <Link/>
in the sidebar would change the URL but wouldn't update the main content area. So rendering the Sidebar
component using a route with no path I thought would always render the Sidebar
AND let me pass the location. However I'm getting this error...
Invariant Violation: A
<Router>
may have only one child element
Here's my code in App.js
import React, { Component } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.css'
import '../node_modules/bootstrap/dist/css/bootstrap-theme.css'
import Sidebar from './components/Sidebar/sidebar'
import SidebarContent from './components/Sidebar/sidebar_content'
import Blank from './components/Blank/blank';
import Course from './components/Course/course';
import { Grid, Col, Row } from '../node_modules/react-bootstrap'
import {
Route,
BrowserRouter as Router,
Switch,
withRouter,
Redirect,
Link
} from 'react-router-dom'
class App extends Component {
render() {
const sidebar = <SidebarContent params={this.props.params}/>
document.body.style.overflow = "hidden"
const sidebarProps = {
sidebar: sidebar,
docked: true,
shadow: false,
touchHandleWidth: 20,
dragToggleDistance: 30,
touch: false,
transitions: false,
pullRight: false,
open: true,
}
const CourseParent = (props) => {
return(<Course courseID={props.courseID}/>);
}
const SidebarParent = (props) => {
return(<Sidebar {...sidebarProps} className="Sidebar" location={props.location}/>);
}
return (
<Router>
<div>
<Grid fluid={true}>
<Row className="show-grid">
<Col className="col-md-2" style={{height: '100vh', width: '175px'}}>
{/* <Sidebar {...sidebarProps} className="Sidebar" location={location}/> */}
<div>
<Route render={({ location }) => (
<Sidebar {...sidebarProps} className="Sidebar" location={location}/>
)}/>
</div>
</Col>
<Col className="col-md-auto">
<Switch>
<Route exact path="/" component={Blank}/>
<Route path="/course/:courseID" component={CourseParent}/>
<Redirect to="/" />
</Switch>
</Col>
</Row>
</Grid>
</div>
</Router>
);
}
}
export default App;
There should be single in your whole app and it contain only a single component. You can find detail about this at here: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.