So I've been struggling with this code. I have a component which accepts a child as a prop, and it is supposed to be the base of all the pages I host.
Base.jsx :
import React from 'react';
import PropTypes from 'prop-types';
import { Link, NavLink } from 'react-router-dom';
const Base = ({ child }) => (
<div>
<div className="top-bar">
<div className="top-bar-left">
<NavLink to="/">React App</NavLink>
</div>
<div className="top-bar-right">
<Link to="/login">Log in</Link>
</div>
</div>
{child.render()} // HERE IS THE CHILD TO RENDER
</div>
);
Base.propTypes = {
child: PropTypes.object.isRequired
};
export default Base;
Then, in app.jsx, where lies the ReactDom.render(), I have this :
import React from 'react';
import ReactDom from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import LoginPag from './components/LoginPag.jsx';
import Base from './components/Base.jsx';
import HomePage from './components/HomePage.jsx';
// for MaterialUI to work properly
injectTapEventPlugin();
const TestLogin = (props) => {
return (<Base child={LoginPag} />);
};
const TestBase = (props) => {
return(<Base child={HomePage}/>)
};
ReactDom.render((<BrowserRouter><MuiThemeProvider muiTheme={getMuiTheme()}>
<div>
<Switch>
<Route exact path="/" component={TestBase} />
<Route exact path="/login" component={TestLogin}/>
</Switch>
</div>
</MuiThemeProvider>
</BrowserRouter>), document.getElementById('react-app'));
Finally, HomePage and LoginPag look alike and here's the HomePage.jsx :
import React from 'react';
import { Card, CardTitle } from 'material-ui/Card';
const HomePage = {
render() {
return (<Card className="container">
<CardTitle title="React Application" subtitle="This is the home page." />
</Card>);
}
};
export default HomePage;
My question now is : Isn't it possible to get rid of these abstractions TestLogin and TestBase ?
My final goal is to have something like this :
<Route exact path="/" component={Base(HomePage)} />, that is to say getting rid of the abstraction layer and directly render this in one line.
Thanks in advance.
EDIT: Thanks to anuragasaurus, I could achieve what I wanted. Can I do it with a class as well ? The class is declared as class LoginPage extends React.Component and has a render() method.
You can use render to display your component inline,
<Route exact path="/" render={()=><Base child={HomePage} />} />
<Route exact path="/login" render={()=><Base child={LoginPage} />}/>
With a simple object AND a class:
const Base = ({ child }) => (
<div>
<div className="top-bar">
<div className="top-bar-left">
<NavLink to="/">React App</NavLink>
</div>
<div className="top-bar-right">
<Link to="/login">Log in</Link>
</div>
</div>
{child}
</div>
);
And
const TestLogin = (props) => {
return (<Base child={<LoginPage/>} />);
};
const TestBase = (props) => {
return(<Base child={<HomePage}/>/>)
};
To answer for the entire question :
<Route exact path="/" render={()=><Base child={<HomePage/>} />} />
<Route exact path="/login" render={()=><Base child={<LoginPage/>} />}/>
Related
I'm trying to develop a slide-out menu with routing function for React. for some reason state = {} isn't setting defining sideDrawOpen what could the reasons for this be thanks for your help. the error I get running yarn start is
"Failed to compile.
./src/App.js
Line 21:45: 'sideDrawerOpen' is not defined no-undef
Search for the keywords to learn more about each error."
import React, { Component } from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import main_page from './components/main_page';
import setup_page from './components/setup_page';
import settings_page from './components/settings_page';
import Error from './components/Error';
import Nav from './components/Navigation/Nav';
import SideDrawer from './components/Navigation/SideDrawer';
import Backdrop from './components/Navigation/Backdrop';
export class App extends Component {
state = {
sideDrawerOpen: false
}
drawerToggleClickHandler = () => {
this.setState((prevState) =>{
return {sideDrawerOpen: !prevState,sideDrawerOpen};
});
};
render() {
let sideDrawer;
let backdrop;
if (this.state.sideDrawerOpen) {
sideDrawer = <SideDrawer />
backdrop = <Backdrop />
}
return (
<div className="App_margin">
<Router>
<div className='App'>
{sideDrawer}
{backdrop}
<Nav />
<Switch>
<Route path='/' component={setup_page} exact/>
<Route path='/main_page' component={main_page} />
<Route path='/settings_page' component={settings_page} />
<Route component={Error} />
</Switch>
</div>
</Router>
</div>
);
}
}
!prevState,sideDrawerOpen has a comma, not a .
So the problem is that I'm new to REACT, I used create-react-app and added a Router function to route between components. Now I created a header which everything was okay with, but I added a hamburger-menu so I could route between my pages and suddenly my Header just got itself duplicated on my webpage.
App.js:
import React, {Component} from 'react';
import { BrowserRouter as Router, Route} from "react-router-dom";
import './App.css';
import './Header.css'
import SideDrawer from "./SideDrawer";
import Header from './Header'
import Backdrop from './Backdrop'
import Home from "./Home";
import LoginPage from "./LoginPage";
import SignupPage from "./SignupPage";
import RegisterEventPage from "./RegisterEventPage";
class App extends Component {
state = {
sideDrawerOpen: false
};
drawerToggleClickHandler = () => {
this.setState((prevState) => {
return {sideDrawerOpen: !prevState.sideDrawerOpen};
});
};
backDropClickHandler = () => {
this.setState({sideDrawerOpen: false});
};
render() {
let sideDrawer;
let backdrop;
if (this.state.sideDrawerOpen) {
sideDrawer = <SideDrawer/>;
backdrop = <Backdrop click={this.backDropClickHandler}/>;
}
return (
<div style={{height: '100%'}}>
<Header drawerClickHandler={this.drawerToggleClickHandler}/>
{sideDrawer}
{backdrop}
<Router>
<Route exact path="/" component={Home}/>
<Route path="/loginPage" component={LoginPage}/>
<Route path="/SignupPage" component={SignupPage}/>
<Route path="/RegisterEventPage" component={RegisterEventPage}/>
</Router>
</div>
);
}
}
export default App;
Header.jsx:
import React, {Component} from 'react';
import DrawerToggleButton from './DrawerToggleButton';
import './Header.css';
class Header extends Component {
render() {
return (
<header className="main_toolbar">
<nav className="toolbar_navigation">
<div>
<DrawerToggleButton click={this.props.drawerClickHandler}/>
</div>
<div className="toolbar_logo">IceBreaker</div>
<div className="spacer"></div>
</nav>
</header>
);
}
}
export default Header;
So if I for example remove from App.js my second header suddenly disappears.
Image of two headers
Render your header inside the router:
I also recomend you to use a switch in your router
You will need to import it :
import { BrowserRouter as Router, Route} from "react-router-dom";
return (
<div style={{height: '100%'}}>
<Router>
<Header drawerClickHandler={this.drawerToggleClickHandler}/>
{sideDrawer}
{backdrop}
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/loginPage" component={LoginPage}/>
<Route path="/SignupPage" component={SignupPage}/>
<Route path="/RegisterEventPage" component={RegisterEventPage}/>
</Switch>
</Router>
</div>
);
I've tried everything but fail to render component when URL changes. No error messages nothing, react-redux is installed but not using it yet, so it can't be the problem. When I check it from to Google chrome React dev tools, nothing happens, there is no match, history vs anything. I couldn't find a solution, is there any way to make it work?
https://codesandbox.io/s/vm3x9n4k67
Here is my NavBar.js. I import NavLink from react-router-dom and implement these
import React from 'react'
import classes from "./NavBar.css";
import { NavLink } from 'react-router-dom';
const NavBar = (props) => {
return (
<div className={classes.NavBar}>
<h1 className={classes.NavBar_list} >foodbase</h1>
<ul className={classes.NavBar_list}>
<NavLink to="/auth"> <li className={classes.NavBar_list_item}>Signin</li></NavLink>
<NavLink to="/"><li className={classes.NavBar_list_item}>Main Page</li></NavLink>
</ul>
</div>
)
}
export default NavBar
this is my Layout.js render property:
render() {
let recipes = [];
if (this.state.recipes.length > 0) {
recipes = this.state.recipes;
}
return (
<div>
<NavBar/>
<SearchBox
onChangeHandler={this.onChangeHandler}
value={this.state.inputValue}
onSearchClick={this.onClickedHandler} />
<section className={classes.SearchSection}>
<ul className={classes.SearchResultArea}>
<SearchResults
Results={recipes}
></SearchResults>
</ul>
</section>
</div>
)
}
and finally app.js:
import React, { Component } from 'react';
import { Switch, Route, BrowserRouter, withRouter } from 'react-router-dom';
import Auth from './components/Auth/Auth';
import SearchBox from './components/SearchBox/SearchBox';
import Layout from './containers/Layout/Layout';
import './App.css';
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<Switch>
<Layout>
<Route path="/auth" component={Auth} />
<Route path="/" exact component={SearchBox} />
</Layout>
</Switch>
</BrowserRouter>
</div>
);
}
}
export default withRouter(App);
I assume that you need to put your Route components directly into Switch and don't forget to render children in Layout. So try this:
app.js:
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<Layout>
<Switch>
<Route path="/auth" component={Auth} />
<Route path="/" exact component={SearchBox} />
</Switch>
</Layout>
</BrowserRouter>
</div>
);
}
}
Layout.js
render() {
// ...
return (
<div>
<NavBar />
{ this.props.children } // <-- your route specific components
</div>
)
}
I have this index.js:
<Provider store={store}>
<Router history={history}>
<App/>
</Router>
</Provider>
this App.js:
<Switch>
<Route exact path="/" component={Home} />
<Route
path="/login"
render={() => <Login userError={this.state.userError} />}
/>
<Route path="/registration" component={Registration} />;
</Switch>
and Home.js:
<div className="Home">
<Header/>
<div className="content">
<Sidenav/>
<Switch>
<Route path="/friends" component={Friends}/>
</Switch>
<Feed/>
</div>
</div>
I want Friends component to be rendered inside content block, but now if I try to reach /friends route via Link I am getting blank page. If I set /friends Route in App.js, it will be OK, but I won't have it in my content class, because it will be another page.
May you give me a hand with that?
Also in feature I will be have more items to display in content, that's why I put Switch in Home.js
Thanks in advance!
Move your content class and <Friends>
The issue you're having is that the component Home is not rendering when you visit /friends because it will only render when you go to /
To fix this just move the Route into the App.js file, along with the content class into the Friends component.
To make this easier, you could make your content class into a component. This way you could wrap it around all of the stuff you render.
Or move <Friends> and wrap content
What I mean by this is that you could also create your own Route component that wraps whatever component passed to it in a Content component. It might look similar to this:
const ContentRoute = ({ component, ...props }) => (
<Route {...props} component={() => (
<Content>
<component />
</Content>
)}>
</Route>
)
You can access demo here
Here what I have done. This demonstrates how to set layout when page's changing.
- src/
-- components/
--- Header.js
--- Sidenav.js
-- pages/
--- Home.js
--- Login.js
--- withBase.js
-- App.js
-- BaseLayout.js
-- routes.js
At first, let's make dummy components.
components/Header
import React from 'react';
export default () => (
<div>
This is Header.
</div>
);
components/Sidenav
import React from 'react';
export default () => (
<div>
This is Sidenav.
</div>
);
Then, pages.
pages/Home
import React from 'react';
import { NavLink } from 'react-router-dom';
import withBase from './withBase';
const Home = () => (
<div>
<p>Welcome Home!!!</p>
<NavLink to="/login">Go to login page</NavLink>
</div>
);
export default withBase(Home);
pages/Login
import React from 'react';
import { NavLink } from 'react-router-dom';
import withBase from './withBase';
const Login = () => (
<div>
<p>You have to login here...</p>
<NavLink to="/">Go home</NavLink>
</div>
);
export default withBase(Login);
pages/withBase
import React from 'react';
export default WrappedComponent => (
class extends React.Component {
componentDidMount() {
this.props.showHeaderSidenav();
}
render() {
return <WrappedComponent />;
}
}
);
As you see, withBase is a HOC. It runs showHeaderSidenav when the page is mounted.
App
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import BaseLayout from './BaseLayout';
import routes from './routes';
export default class extends React.Component {
state = {
withHeaderSidenav: true
}
showHeaderSidenav = (withHeaderSidenav = true) => {
this.setState({ withHeaderSidenav });
}
render() {
return (
<BaseLayout withHeaderSidenav={this.state.withHeaderSidenav}>
<Switch>
{routes.map(route => (
<Route
exact
key={route.path}
path={route.path}
render={() => (
<route.component
showHeaderSidenav={() => this.showHeaderSidenav(route.withHeaderSidenav)}
/>
)}
/>
))}
</Switch>
</BaseLayout>
);
}
}
BaseLayout
import React from 'react';
import Header from './components/Header';
import Sidenav from './components/Sidenav';
export default ({ withHeaderSidenav, children }) => (
<div>
{withHeaderSidenav && <Header />}
<div className="content">
{withHeaderSidenav && <Sidenav />}
{children}
</div>
</div>
);
We can say that BaseLayout is like a wrapper. It contains dynamic components which will be shown based on withHeaderSidenav prop.
Finally...
routes
import Home from './pages/Home';
import Login from './pages/Login';
export default [
{
path: '/',
component: Home,
withHeaderSidenav: true
},
{
path: '/login',
component: Login,
withHeaderSidenav: false
},
];
You could have moved(declared) content component inside Friends component. I do not see the reason why content component should live outside of Friends component. You can declare content component inside any component that needs it.Content component does not have to mess with routing implementation
I am new to React and having issues with router. I am just learning from this tutorial: https://medium.com/#thejasonfile/basic-intro-to-react-router-v4-a08ae1ba5c42
Below is the code that is being called from my index.html. When I click on the link 'Show the list', the url changes from localhost:8080 to localhost:8080/list but doesn't really change the context of the page. I am not sure what is going or what I am doing wrong here. Any ideas?
Scripts.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Title, App} from './Components/App';
import { BrowserRouter as Router, Route } from 'react-router-dom';
ReactDOM.render(
<Router>
<div>
<Route exact path="/" component={Title} />
<Route path="/list" component={App} />
</div>
</Router>
, document.getElementById('app'));
App.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
const Title = () => {
return (
<div className="title">
<h1>React Router demo</h1>
<Link to="/list">
<button>Show the List</button>
</Link>
</div>
)};
const List = () => {
return (
<div className="nav">
<ul>
<li>list item</li><li>list item</li></ul><Link to="/"><button>Back Home</button></Link></div>)
}
module.exports = {
Title,
List
};
I refactored your code a bit, you should not render the App component for a single page rather your app component should have all the routes like how I made it below. Then as needed add Link throughout your components when you need to navigate and then add the routes in App respectively.
import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { Link } from 'react-router-dom';
class App extends Component {
constructor() {
super();
}
render() {
return (
<Router>
<div>
<Route exact path='/home' render={()=> <Title />} > </Route>
<Route exact path='/list' render={() => <List />} > </Route>
</div>
</Router>
);
}
}
const Title = () => {
return (
<div className="title">
<h1>React Router demo</h1>
<Link to="/list">
<button>Show the List</button>
</Link>
</div>
)};
const List = () => {
return (
<div className="nav">
<ul>
<li>list item</li><li>list item</li></ul><Link to='/home'><button>Back Home</button></Link></div>)
}
render(<App />, document.getElementById('app'));
document.getElementById is usually root looks like you changed it to app which is fine.