`react-router` warning solution and passing root props to sub routes - javascript

Sometime I was sawing the well known warning, browser.js:49 Warning: [react-router] You cannot change <Router routes>; it will be ignored and I found two trend issues that friends discussed about this issue and the solution is const routes components and putting them inside Router component.
https://github.com/ReactTraining/react-router/issues/2704
https://github.com/reactjs/react-router-redux/issues/179
Just like below:
you will see warning with this code:
class Root extends Component {
render() {
return (
<Router history={browserHistory} createElement={this.createElement}>
<Route component={App}>
<Route path="/" component={MainPage}/>
<Route path="/page2" component={Page2}/>
<Route path="/settings" component={SettingsPage}/>
</Route>
</Router>
)
}
}
but you won't see warning with this code:
const routes = (
<Route component={App}>
<Route path="/" component={MainPage}/>
<Route path="/page2" component={Page2}/>
<Route path="/settings" component={SettingsPage}/>
</Route>
);
class Root extends Component {
render() {
return (
<Router history={browserHistory} createElement={this.createElement}>
{routes}
</Router>
)
}
}
This is OK, awesome solution to vanish [react-router] warning, and for Root Component changing state the routes was static and you won't see any warnings. BUT my issue is: I pass Root Component props to each Route and I can not do the above solution 😞 ,
I must put App Route inside Router so with this method absolutely this is not solution method and I will saw the known warning again, see my router code:
export default class AppRoutes extends Component {
render() {
return (
<Router history={hashHistory}>
<Route path="/" {...this.props} component={App}>
<IndexRoute component={Home} {...this.props}/>
<Route path="/transaction" component={Transaction} {...this.props}/>
<Route path="/users-management" component={UsersManagement} {...this.props}/>
<Route path="/issues" component={Issues} {...this.props}/>
<Route path='/not-found' component={NotFound}/>
<Route path='/settlement-management' component={SettlementManagement} {...this.props}/>
<Route path='/categories-management' component={CategoriesManagement} {...this.props}/>
<Route path='/gifts-management' component={GiftsManagement} {...this.props}/>
<Redirect from='/*' to='/not-found'/>
</Route>
</Router>
);
}
}
And the Root Component render code is:
render(){
return(
<AppRoutes {...this}/>
);
}
I passed this as a props to AppRoutes component and I need to pass inherited this.props to sub Routes and use them. how I could won't see warning and pass props to any Routes?
One of my solution is that, I write all Routes as static and call Root Component props directly inside each component, but how? I don't know how I can call and keep props of Root Component inside the component that need to have props of Root Component as the component is not direct Root Component children?

You can use render route prop instead of component to pass props to your components :
<Route path="/transaction" render={() => <Transaction {...this.props} />} />
Edit : Or this to also pass route props :
<Route path="/transaction" render={(routeProps) => <Transaction parentProps={this.props} {...routeProps} />} />
(I think it's better to pass individual custom parent props to not enter in conflict with routeProps)

Related

I want to test if the routes exist

I want to test if the routes exist in the component. App should render the specific component on the specific path.
App.js
return (
<Router>
<Header jsTrendingTopics={this.props.data} />
<Switch>
<Route exact path="/" render={() => <Dashboard jsTrendingTopics={this.props.data} />} />
<Route exact
path="/language/:languagename"
render={(props) => this.handleTopic(props)
}
/>
</Switch>
</Router>
)
}
I expect the test to return the component that should render on that specific route.
I think MemoryRouter with initialEntries={['/]} is what you are looking for.
import Dashboard from ...
jest.mock('path to Dashboard component');
Dashboard.mockImplementationOnce(() => <div>Dashboard</div>);
render(
<MemoryRouter initialEntries={['/']}>
<App/>
</MemoryRouter>
);
expect(screen.getByText("Dashboard").toBeInTheDocument()
You can read this document for more examples
https://javascript.plainenglish.io/testing-react-router-with-jest-bc13d367bad

Render Same Component With Multiple Paths React Router Dom

I was looking for the simplest way to render the same component but from different paths.
I have the following so that both "/" and "/login" render the Login component.
import React from "react";
import { Route, Switch, Redirect } from 'react-router-dom';
import './App.scss';
import Login from "../../login/Login";
const App = () => {
return (
<div className="App">
<div className="App-container">
<Switch>
<Route exact path={["/", "/login"]} component={() =>
<Login login={true} />}/>
<Redirect to="/" />
</Switch>
</div>
</div>
);
}
export default App;
This does appear to work, however, it returns an error in the console.
Warning: Failed prop type: Invalid prop 'path' of type 'array' supplied to 'Route', expected 'string'.
I'm trying to do this...
<Route exact path={"/"} component={() => <Login login={true} />}/>
<Route exact path={"/login"} component={() => <Login login={true} />}/>
But with a shorter method, is this possible with react-router-dom? Any help would be greatly appreciated
You could create an array that contains the paths / and /login and use map on that array to render the same thing for both paths.
<Switch>
{["/", "/login"].map(path => (
<Route
key={path}
exact
path={path}
render={() => <Login login={true} />}
/>
))}
<Redirect to="/" />
</Switch>
If you wish to render the same component on the several routes, you can do this by specifying your path as a regular expression
lets say you want to display 'Home' component for 'Home', 'User' and 'Contact' components then here is code.
<Route path="/(home|users|contact)/" component={Home} />

Nested <Route> components are not rendering properly in react-redux-router [duplicate]

I am trying to group some of my routes together with React Router v4 to clean up some of my components. For now I just want to have my non logged in routes group together and my admin routes grouped together but the following doens't work.
main.js
const Main = () => {
return (
<main>
<Switch>
<Route exact path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main;
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
export default Public;
The Greeting component shows at "localhost:3000/", but the SignupPage component does not show at "localhost:3000/signup" and the Login component doesn't show at "localhost:3000/signup". Looking at the React Dev Tools these two routes return Null.
The reason is very obvious. for your route in main.js, you have specified the Route path of Public component with exact exact path='/' and then in the Public component you are matching for the other Routes. So if the route path is /signup, at first the path is not exact so Public component is not rendered and hence no subRoutes will.
Change your route configuration to the following
main.js
const Main = () => {
return (
<main>
<Switch>
<Route path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
Also when you are specifying the nested routes these should be relative to the parent Route, for instance if the parent route is /home and then in the child Route you wish to write /dashboard . It should be written like
<Route path="/home/dashboard" component={Dashboard}
or even better
<Route path={`${this.props.match.path}/dashboard`} component={Dashboard}

react router onChange

How to pass new props when route changed?
I need change class depends on route.
export class Routes extends React.Component<any, any> {
constructor(props:any){
super(props);
}
handleChange = (prevState, nextState, replaceState) => {
console.log(nextState.location.pathname);
};
render(){
return(
<Router {...this.props}>
<Route path="/" onChange={this.handleChange} component={Miramir}>
<Route path="/about">
<IndexRoute component={Miramir}></IndexRoute>
</Route>
<Route path="/contact">
<IndexRoute component={Miramir}></IndexRoute>
</Route>
<Route path="/profile">
<IndexRoute component={Profile} />
<Route path="/profile/update" component={ProfileUpdate} />
<Route path="/profile/login" component={LogInPage} />
</Route>
</Route>
</Router>
)
}
}
I'm trying to get props in my Miramir component and check location.pathname
For example: On my route / i want header class home-page and on /profile route want profile-page class.
But when i change routes location.pathname has / route
How to check update props?
I need nextState.location.pathname in my Miramir component
You can provide onEnter hook when route is about to change.
e.g
<Route
path="/profile/update"
component={ProfileUpdate}
onEnter={onProfileUpdate}
/>
Then you can define that function onProfileUpdate
function onProfileUpdate(nextState, replace, callback) {
replace({
pathname: '/transition path name here',
state: { nextPathname: nextState.location.pathname }
});
}
If your component is a route component, like it is in your case, it will get some props injected into it by the Router itself. You'll get your current location, params and so on, so you could simply read that in your render method and act accordingly.
https://github.com/ReactTraining/react-router/blob/master/docs/API.md#injected-props
If you need to access something in a component living deeper in your tree, you could wrap it with the withRouter HOC.
https://github.com/ReactTraining/react-router/blob/master/docs/API.md#withroutercomponent-options

How to get the prams value over the link router in react

I have this link in main component how to get the value in the player component:
<Link to="/player" params={{ testvalue: "hello" }}
className="btn">watch</Link>
class Player extends React.Component{
render(){
alert(this.params.testvalue);
return(
<div></div>
);
}
}
This is a route file
<Route path="/" component={App}>
<IndexRoute component={main}/>
<Route path="/player" component={Player}/>
</Route>
with react router it passes a location object down as props, should be able to access the query using
this.props.params.testvalue
in you Player component
The problem with your code is that you are passing a param with
<Link to="/player" params={{ testvalue: "hello" }}
className="btn">watch</Link>
but you are not receiving it in the Route. Change you route like
<Route path="/" component={App}>
<IndexRoute component={main}/>
<Route path="/player/:value" component={Player}/>
</Route>
Then use
this.props.params.testvalue
in your Player component.

Categories

Resources