React JS refresh page every time clicking on menu item using route - reactjs

I am new to React JS and I am currently building a simple application. I am using Route in order to navigate between components and everything work fine, but if I am on a page and I click again in the menu to navigate to the page, it doesn't refresh its content.
I just want the component to refresh its content every time I click on the item menu.
This is my sidebar class:
class Sidebar extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Router>
<Route render={({ location, history }) => (
<React.Fragment>
<SideNav
onSelect={(selected) => {
const to = '/' + selected;
if (location.pathname !== to) {
history.push(to);
}
}}>
<SideNav.Toggle />
<SideNav.Nav>
<NavItem eventKey="Cars">
<NavIcon>
Cars
</NavIcon>
</NavItem>
<NavItem eventKey="Bicycles">
<NavIcon>
Bicycles
</NavIcon>
</NavItem>
</SideNav.Nav>
</SideNav>
<main>
<Switch>
<Route exact path="/" component={props => <Home />} />
<Route
exact path="/Cars"
render={() => !isAllowed ?
<Home /> :
<Cars/>
} />
<Route
exact path="/Bicycles"
render={() => !isAllowed ?
<Home /> :
<Bicycles />
} />
</Switch>
</main>
</React.Fragment>
)}
/>
</Router>
)
}
}
This is my Cars Component class:
import React, { Component } from 'react';
class Cars extends Component {
render() {
return (
<div style={{ textAlign: 'center', marginLeft: '295px' }} >
<form>
<h1>Hello</h1>
<p>Enter your car name:</p>
<input
type="text"
/>
</form>
</div>
)
}
}
export default Cars;
For ex. if I text something in input and after that I click on the item menu, I want that input to be refreshed.

In order to "refresh" (or in React world called Re-render) the content of the component you need to change it's state, and that is how React works. As I can see you don't have any state in your component so if you can specify what you wanna "refresh" we can help you.
The heart of every React component is its “state”, an object that determines how that component renders & behaves. In other words, “state” is what allows you to create components that are dynamic and interactive.
Quick example from somewhere on the internet :
import React from 'react';
class Person extends React.Component{
constructor(props) {
super(props);
this.state = {
age:0
this.incrementAge = this.incrementAge.bind(this)
}
incrementAge(){
this.setState({
age:this.state.age + 1;
});
}
render(){
return(
<div>
<label>My age is: {this.state.age}</label>
<button onClick={this.incrementAge}>Grow me older !!<button>
</div>
);
}
}
export default Person;
The age of inside of the label is being Re-rendered (or "refresh") every time when the user clicks on it since its state is changing.
Here is an official documentation and I would recommend you read it, it will clarify a lot of issues you are facing.
https://reactjs.org/docs/state-and-lifecycle.html

Related

How to set a state variable in the parent of a React Route?

I am having fun implementing routing in my app, but find it hard to set a page title in the parent with the name of the screen that Route is rendering, like this:
class App...
setTitle(title) {
this.state.screentitle = title
this.setState(this.state)
}
...
<h1>{this.state.title}</h1}
...
<Route path='/Search' render={props => <ScreenSearch setTitle={this.setTitle} {...props} />} />
and each child holds the actual title text, like:
class ScreenSearch...
componentDidMount() {
this.props.setTitle("Search");
}
While this actually works, I would prefer to keep the title texts for all child screens in the parent, together with all Route rules. After all, the child objects should do just their job, like implementing a search page, but have no need to know what it is called at the parent level.
Also, this seems a complex way with too much code to just set a stupid title.
As a beginner with React Route, I would like to ask if there is a better way.
You can implement a Layout component that will have shared items on it like page title,navigations etc.
Layout Component
class DefaultLayout extends React.Component{
render() {
return (
<div>
<div className="header">
<h1>Company Name</h1>
<Navigation />
</dv>
<div className="content">
<h1>{this.props.title}</h1>
{this.props.children}
</div>
<div className="footer">
<p>Copyright (c) 2014 Company Name</p>
</div>
</div>
);
}
};
module.exports = DefaultLayout;
and the child page
var React = require('react');
var DefaultLayout = require('./DefaultLayout');
class PageOne extends React.Component{
this.state={
title:"Page 1"
}
render() {
return (
<DefaultLayout title={this.props.title}>
<p>The page's content...</p>
<p>goes here.</p>
</DefaultLayout>
);
}
}
This is a way to implement it, if you have many routes you can create your own Route component where you give the title as a prop
<Route path='/Search' render={props => {
this.state.screentitle!==this.setTitle && this.setTitle(this.setTitle)
return <ScreenSearch {...props} />}
/>
After seeing your comment I understand you want to remove the set Title so you will need the location from react-router and an object something like this:
let routeTitles = {
/'search': 'The search' ,
'/jobs': 'Look for a job'
}
<Title>{routeTitles[this.props.location.pathname]}</Title>

My component is creating TypeError: Cannot read property 'click' of null

This problem is related with my Buy_Item Component. The Urban Outfitter logo at the top left is supposed to bring you back to the home page. It works completely fine with my other components, except this one. When I click it gives me:
class App extends Component {
render() {
return (
<BrowserRouter>
<div className="App">
<Header/>
<Route exact path="/" render = {() => <Featured/> } />
<Route path="/items-available" render = {() => <Items_Available item_info={<Item_Info/>}/> } />
<Route path="/buy-item" render = {() => <Buy_Item buy_item_info={<Buy_Item_Info/>}
item_info={<Item_Info/>}/> } />
<Footer/>
</div>
</BrowserRouter>
);
}
}
export default App;
Here's what the "Urban Outfitter" logo does in my Header Component:
<div id="nav_logo_container">
<Link to="/">
<picture>
<source media="(min-width:768px)" srcset={uo_logo} />
<source srcset={uo_logo_smaller_screen} />
<img id="nav_logo" src={uo_logo} alt="Urban Outfitters Logo" />
</picture>
</Link>
</div>
Here's my Github repo, if it helps: https://github.com/mattfrancis888/project_2/tree/item_info/src
You have it all wrong in your Buy_Item component
Never call setState inside the render() method as it could cause an infinite loop. This is because calling setState will always lead to a re-render unless shouldComponentUpdate returns false.
Try this...
const imgDic = {
0: item_1,
1: item_1_alt,
2: item_1_alt2,
3: item_1_alt3,
4: item_1_alt4,
5: item_1_alt5
};
class Buy_Item extends React.Component {
constructor(props) {
this.state = {
radioStatus: null,
currentImg: item_1
};
this.handleRadioClick = this.handleRadioClick.bind(this);
}
handleRadioClick(radioId) {
this.setState({
radioStatus: radioId,
currentImg: imgDic[radioId]
});
}
render() {
// the rest of render code goes here...
}
}

ReactJS, React-Router: Calling parent function

I am working on a React App, trying to call a parent method from a child component, some code of the parent component below:
class NavigationBar extends Component {
constructor(props){
super(props);
this.state={isLoggedIn: false};
}
updateLoginState(){
alert("Login from NavigationBar");
}
GetBar() {
//const isLoggedIn = this.props.isLoggedIn;
if (false){ //isLoggedIn
return this.UserNavBar();
}
return this.StrangerNavBar();
}
StrangerNavBar(){
return (
<div>
<HashRouter>
<div>
{/* ... */}
<div className="content">
<Route exact path="/LoginCC" loginUpdate={this.updateLoginState} component={LoginCC} />
</div>
</div>
</HashRouter>
</div>
);
}
render() {
return (
this.GetBar()
);
}
}
export default NavigationBar;
This component is supposed to redirect the user to different content pages based on whether or not he is logged in, using a Router. If a button is clicked in LoginCC.js the method updateLoginState should be invoked which just displays a message for now. The child content page LoginCC.js looks as follows:
class LoginCC extends Component {
constructor(props){
super(props);
this.state = {isLoggedIn: false};
}
render() {
return (
<div>
<HashRouter>
{/* ... */}
<Button variant="primary" size="lg" block onClick={this.props.loginUpdate}>
Log in
</Button>
{/* ... */}
</HashRouter>
</div>
);
}
}
export default LoginCC;
I passed the method reference as a prop to LoginCC when rendering this component using the Router, so a message should pop up if I press the button, but nothing happens.
Am I passing the prop incorrectly or something else I've missed? I'm new to React so any help is appreciated.
Route doesn't pass any custom props to components. You should use other method to pass functions.
One of solutions is:
<Route exact path="/LoginCC" render={
props => <LoginCC {...props} loginUpdate={this.updateLoginState}/>
} />
Note that updateLoginState will not get this when called. You should either bind it or declare it as an arrow function to get the correct this.
Also check the Context documentation.

React Component does not render when clicking CardActionArea from Material UI

I'm running into a weird issue that I've never run into before.
I'm using Material UI components, specifically CardActionArea paired with
Redirect from react-router-dom
Upon clicking the CardActionArea I want to redirect my users to a detail screen of the component they just clicked.
The detail view sometimes renders and sometimes it doesn't. For example, if I click on the CardActionArea the detail view does not render, but if I navigate directly to the URL, the detail view does render.
This is the relevant code:
// Dashboard.js
return (
<Grid container spacing={40} className={classes.root}>
<TopMenu></TopMenu>
<Router>
<Route exact path="/dashboard/v/:videoId" component={VideoDetail} />
</Router>
<Router>
<Route exact path="/dashboard" component={(YouTubeVideoGallery)} />
</Router>
</Grid>
);
The CardActionArea is here:
constructor(props) {
super(props);
this.state = {
redirect: false
};
this.handleCardActionClick = this.handleCardActionClick.bind(this);
}
handleCardActionClick = () => {
this.setState({redirect: true});
}
render() {
const { classes } = this.props;
const date = moment(this.props.video.publishedAt);
if (this.state.redirect) {
return (<Redirect to={`/dashboard/v/${this.props.video.id}`} />)
}
return (
<Card className={classes.card}>
<CardActionArea onClick={this.handleCardActionClick}>
<CardHeader
title={
(this.props.video.title.length > 21) ?
this.props.video.title.substr(0, 18) + '...' :
this.props.video.title
}
subheader={`${date.format('MMMM DD[,] YYYY')} - Views: ${this.props.video.viewCount}`}
/>
<CardMedia
className={classes.media}
image={this.props.video.thumbnails.medium.url}
title={this.props.video.title}
/>
</CardActionArea>
</Card>
);
}
I'm not really sure what the problem is.
First thing handleCardActionClick is an arrow function so you no need to do binding in constructor. That can be removed
To redirect on onclick do something like below
render(){
const url = `/dashboard/v/${this.props.video.id}`;
return(
<div>
{this.state.redirect && <Redirect to={url} />}
</div>
)
}

Timeout for component unmount

Okay, I have an idea about making comfortable and native page transitions with React. I made an example of how pages must transition between themselves - you can check it here.
And then I started to programming it with React. And I have stalled.
Let's say I have a component Scene:
export default class Scene extends React.Component {
constructor(props) {
super(props)
this.state = {
beforeUnmount: false
}
}
render() {
return (
<div
className={ classNames({ "scene-container": true, "scene-unmount": this.state.beforeUnmount })}
style={{ backgroundColor: this.props.color}}>
<h1 style={{ marginTop: "25%", textAlign: "center" }}> Scene { this.props.id } </h1>
{ this.props.children }
</div>
)
}
}
and a TestPage view that uses this Scene (AnotherTestPage is mostly the same):
export default class TestPage extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<Helmet
title={`Scene ${this.props.params.id}`}
meta={[{name: 'description', content: 'Index page'}]}
/>
<Scene id={ this.props.params.id } color= {`#${this.props.params.color}`}>
<DefaultLink to="/" text="Go to Index" />
<DefaultLink to="/another" text="Go to Another" />
</Scene>
</div>
)
}
}
and the Router
export function createRoutes(history, store) {
return (
<Router>
<Route component={App}>
<Route path='/' component={IndexPage} />
<Route path='/forms' component={Forms} />
<Route path='/scenes/:id/:color' component={TestPage} />
<Route path='/another' component={AnotherTestPage} />
</Route>
</Router>
)
}
Before current view is being unmounted, there must be fade-out animation of Scene, and at the same time next view should fade-in. And my problem is i don't know how to do it, how to timeout unmount of the view. Will be very thanksful if anyone will help me!
Animations in React are done with the help of React ad-on: react-addons-css-transition-group
There's an example in React Router that accomplishes what you're trying to achieve (animation between page transitions): https://github.com/ReactTraining/react-router/tree/master/examples/animations

Resources