React does not render correct on page refresh - javascript

I am using ant design and server side render in my React project.
My header rendered according to user authentication status. If user is authenticated appHeader is used.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Layout, BackTop, Button } from 'antd'
import LandingHeader from './_Landing/Header/LandingHeader'
import AppHeader from './Common/AppHeader'
import { withRouter } from 'react-router-dom'
import { bool, object } from 'prop-types'
const { Content, Footer } = Layout;
class AppLayout extends Component {
constructor (props) {
super(props)
this.state = {}
}
render () {
const { children, location } = this.props
const isLoggedIn = this.props.isAuthenticated
let AppHeaderConditional = null
if (isLoggedIn && location.pathname != '/' && location.pathname != '/login' && location.pathname != '/signup') {
AppHeaderConditional = <AppHeader />
} else {
AppHeaderConditional = <LandingHeader />
}
return (
<div className='landing-page-wrapper' data-pathname={`${location.pathname}`}>
{AppHeaderConditional}
<Layout>
<Content>
{children}
</Content>
</Layout>
<BackTop>
<Button type='primary' shape='circle' icon='up-circle-o' size='large' />
</BackTop>
<Footer className='footer' style={{ textAlign: 'center' }} >
© 2017 -
</Footer>
</div>
)
}
}
AppLayout.propTypes = {
isAuthenticated: bool,
children: object,
location: object
}
const mapStateToProps = state => {
return {
isAuthenticated: state.user.isAuthenticated
}
}
export default withRouter(connect(mapStateToProps)(AppLayout))
On full page load (i mean navigating from home to member page with link ) it renders correct with className but on page refresh this class not added to header. And console log gives an error "Warning: Did not expect server HTML to contain a..."
I made research about this console warning but nothing helped me. I tried pure:false (https://github.com/reactjs/react-redux/blob/master/docs/troubleshooting.md), and some other things but i cant solve the issue.

You have to use staticRouter on server and browserRouter on the client - https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/server-rendering.md

I found the solution. All you need is below. Because somehow page renders itself second time on client, i don't know why but this the solution.
componentDidMount () {
this.setState({ mounted: true })
}

Related

How to detect if another component is present in the document?

I have a site built with React Static that has a Header component that is always present. Depending on if the current page has a hero component or not, the Header should be either light or dark.
The Header is rendered outside of the routes and the useEffect is triggered before the children is rendered. This is probably because of the routing.
This is the current code:
// App.js
import React, { useState, useEffect } from 'react'
import { Root, Routes } from 'react-static'
export default () => {
const [useDarkTheme, setUseDarkTheme] = useState(false);
useEffect(() => {
if (typeof document !== "undefined") {
const heroPresent = document.querySelectorAll(".o-hero").length > 0;
console.log("The hero is present: " + heroPresent);
setUseDarkTheme(!heroPresent);
}
})
return (
<Root>
<React.Suspense fallback={ <em>Loading...</em> }>
<Header useDarkTheme={ useDarkTheme } />
<Routes default />
</React.Suspense>
</Root>
);
}
What will be rendered at <Routes default /> is the static pages configured in React Static's static.config.js.
Below is an example of the Hero component:
// Hero.js
import React from "react";
export default () => {
console.log("This is the Hero rendering. If this exist, the Header should be dark.");
return (
<div className="o-hero">
<p>Hero!</p>
</div>
);
}
When I run the application and look at the logs this is what I get:
The hero is present: false
This is the Hero rendering. If this exist, the Header should be dark.
How could I somehow detect the presence of the Hero from the Header although the Hero is in a router and the Header is not? This feels like quite a common use case, but I could not find any info on the interwebs.
Thanks in advance!
So I ended up using useContext to provide all children with a getter and a setter for the Header's theme (dark or light). The solution is very much inspired from this answer. The solution looks like this:
// App.js
import React, { useState, useContext } from 'react'
import { Root, Routes } from 'react-static'
import { HeaderThemeContext } from "./context";
export default () => {
const { theme } = useContext(HeaderThemeContext);
const [headerTheme, setHeaderTheme] = useState(theme);
return (
<Root>
<React.Suspense fallback={ <em>Loading...</em> }>
<HeaderThemeContext.Provider value={ { theme: headerTheme, setTheme: setHeaderTheme } }>
<Header theme={ headerTheme } />
<Routes default />
</HeaderThemeContext.Provider>
</React.Suspense>
</Root>
);
}
// Hero.js
import React from "react";
import { headerThemes, setHeaderTheme } from "./context";
export default () => {
setHeaderTheme(headerThemes.DARK);
console.log("This is the Hero rendering. If this exist, the Header should be dark.");
return (
<div className="o-hero">
<p>Hero!</p>
</div>
);
}
// context.js
import React, { createContext, useContext } from "react";
export const headerThemes = {
LIGHT: "light",
DARK: "dark",
};
export const HeaderThemeContext = createContext({
theme: headerThemes.LIGHT,
setTheme: () => {}
});
// This is a hook and can only be used in a functional component with access to the HeaderThemeContext.
export const setHeaderTheme = theme => useContext(HeaderThemeContext).setTheme(theme);
This gives global access to set and get the header theme, which might not be optional, but it works for now and I think it's fine. Please let me know if there is a better way of doing this.

React with Firebase - splitting authorisation between CRUD actions

I am trying to use react with firebase to make an app that allows all users to read everything and some users to write to some functions.
At the moment, I have my firestore security rules set to allow all users to read and write everything, and then I have a withAuthorisation wrapper that I want to put around a component that contains a link to make write a new document. I know this isn't secure, but I'm just trying to get the hang of how to separate the code so that I can build view layers that render the content in line with the permissions I write.
At the moment I have a references list, which is an index of all the references created. At the bottom of that list, I have a component called 'AddReference' which is a link to the form to make a new reference.
The list is not wrapped in my withAuthorisation wrapper. The AddReference component is wrapped.
I am expecting to be logged out and render the list to all users - (everyone can read the index) but a logged out user should not see the AddReference link.
Instead, the entire list is blocked behind an authentication redirect.
My list of all the references has:
import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { compose } from 'recompose';
import { withFirebase } from '../../Firebase/Index';
import * as ROUTES from '../../../constants/Routes';
import { ReferencesList } from './ReferencesList';
import { Layout, Typography, Card, List, Button, Divider } from 'antd';
import {ReferencesForm} from './Form';
import AddReference from './AddReference';
const { Content } = Layout
const { Title, Paragraph, Text } = Typography;
class ReferencesPage extends Component {
render() {
return (
<div>
<Content
style={{
background: '#fff',
padding: 24,
margin: "auto",
minHeight: 280,
width: '90%'
}}
>
<ReferencesList/>
<br/>
<AddReference />
</Content>
</div>
);
}
}
export default ReferencesPage;
My AddReference component has:
import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { compose } from 'recompose';
import { withFirebase } from '../../Firebase/Index';
import * as ROUTES from '../../../constants/Routes';
import { ReferencesList } from './ReferencesList';
import { Layout, Typography, Card, List, Button, Divider } from 'antd';
import {ReferencesForm} from './Form';
import { AuthUserContext, withAuthorization, withEmailVerification } from '../../Session/Index';
const { Content } = Layout
const { Title, Paragraph, Text } = Typography;
const AddReference = () => (
<AuthUserContext.Consumer>
{authUser => (
<div>
<Divider></Divider>
<div style={{
display: "flex",
justifyContent: "center"
}}>
<Link to={ROUTES.REFERENCESFORM}>Add a Reference</Link>
</div>
</div>
)}
</AuthUserContext.Consumer>
);
const condition = authUser => !!authUser;
export default compose(
// withEmailVerification,
withAuthorization(condition),
)(AddReference);
My withAuthorisation wrapper has:
import React from 'react';
import { withRouter } from 'react-router-dom';
import { compose } from 'recompose';
import { withFirebase } from '../Firebase/Index';
import AuthUserContext from './Context';
import * as ROUTES from '../../constants/Routes';
const withAuthorization = condition => Component => {
class WithAuthorization extends React.Component {
// componentDidMount() {
// this.listener =
this.props.firebase.auth.onAuthStateChanged(authUser => {
// if (!condition(authUser)) {
// this.props.history.push(ROUTES.SIGN_IN);
// }
// });
// }
componentDidMount() {
this.listener = this.props.firebase.onAuthUserListener(
authUser => {
if (!condition(authUser)) {
this.props.history.push(ROUTES.SIGN_IN);
}
},
() => this.props.history.push(ROUTES.SIGN_IN),
);
}
componentWillUnmount() {
this.listener();
}
render() {
return (
<AuthUserContext.Consumer>
{authUser =>
condition(authUser) ? <Component {...this.props} /> : null
}
</AuthUserContext.Consumer>
);
}
}
return compose(
withRouter,
withFirebase,
)(WithAuthorization);
};
export default withAuthorization;
Is it possible to have a component that is wrapped inside an authorisation requirement rendered on a page that is not wrapped? I still want to show the content of the list (other than the AddReference component) for users that do not satisfy the authorisation condition.
1> how to implement permissions in an optimize way ?
Answer:
Best practice for React Router user roles (Firebase)
Role-Based Access Control (RBAC) and React Apps.
2> Is it possible to have a component that is wrapped inside an authorisation requirement rendered on a page that is not wrapped? I still want to show the content of the list (other than the AddReference component) for users that do not satisfy the authorisation condition.
Short Answer: Yes, make the page accessible to all users and hide the content of the page which should not be visible to public.
Answer: Well, we need to have a global state ( REDUX, localStorage, etc ) in which we will store user roles ( guest, login etc ) at the time initialization. then when we need to hide an element from component, we just have to check for a value like below
//set state.userRole from globalState in init function.
(this.state.userRole == 'login') ?
<Icon name='md-log-out' style={styles.logoutIcon} button onPress={() =>
Alert.alert(
'Log out',
'Do you want to logout?',
[
{ text: 'Cancel', onPress: () => { return null } },
{
text: 'Confirm', onPress: () => {this.logout()}
},
],
{ cancelable: false }
)
}/>
:
<View />;

this.props.match.params passed into child component after authorisation

I have recently started building a big project on React using also a Firebase with authentication and I cannot quite understand the relation between the react-router-dom links and React components.
I am struggling with getting the
this.props.match.params // which is going to be 2018 / 2019 / 2020... etc
in the component, which renders as a dynamic route (like unique post component).
I have tried to use only a simple class component and this works but the problem is, without the authentication everyone can access this admin route and everyone would be allowed to edit and delete data there. I want it to be accessed only by authenticated users. (Admins)
So this is how my piece of code looks like:
Main component: (where the link is)
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
class SeasonBox extends Component {
render() {
return (
<Link className='seasonbox' to={`/adminseason/${this.props.season}`}>
<p className='seasonbox__season'>{this.props.season}/{this.props.season+1}</p>
</Link>
)
}
}
export default SeasonBox;
And the component that renders after the link is clicked:
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import { compose } from 'recompose'
import { withAuthorisation } from '../Session'
import { withFirebase } from '../Firebase'
const AdminMatchesBox = ({authUser}) => (
<div>{authUser ? <AdminMatchesBoxAuth /> : <AdminMatchesBoxNonAuth />} </div>
)
class AdminMatchesBoxAuth extends Component {
render() {
return (
<div>
Hey I am the season {this.props.match.params}!
<Link to={'/adminmatches'}>Wróć</Link>
</div>
)
}
}
const AdminMatchesBoxNonAuth = () => (
<div>
<h1>You do not have permission to visit this page.</h1>
</div>
)
const mapStateToProps = state => ({
authUser: state.sessionState.authUser
});
const condition = authUser => !!authUser
export default compose(withAuthorisation(condition), connect(mapStateToProps),withFirebase)(AdminMatchesBox);
So if I don't use authorisation, and I use only a single class component I can get this.props.match.params -> which is the id of the website and I need it to access data from the database.
However, I want it to not be visible by not logged users and I had to process it through the authorisation process.
I am receiving an error
Cannot read property 'params' of undefined.
I have no clue how to pass match.params into the AdminMatchesBoxAuth component.
Could anyone advice?
By wrapping withRouter you able to access params
Try this
import { withRouter } from "react-router";
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import { compose } from 'recompose'
import { withAuthorisation } from '../Session'
import { withFirebase } from '../Firebase'
const AdminMatchesBox = ({authUser}) => (
<div>{authUser ? <AdminMatchesBoxAuth /> : <AdminMatchesBoxNonAuth />} </div>
)
class AdminMatchesBoxAuth extends Component {
constructor (props){
super(props)
}
render() {
return (
<div>
Hey I am the season {this.props.match.params}!
<Link to={'/adminmatches'}>Wróć</Link>
</div>
)
}
}
const AdminMatchesBoxNonAuth = () => (
<div>
<h1>You do not have permission to visit this page.</h1>
</div>
)
const mapStateToProps = state => ({
authUser: state.sessionState.authUser
});
const condition = authUser => !!authUser
export default compose(withRouter, withAuthorisation(condition), connect(mapStateToProps),withFirebase)(AdminMatchesBox)

React/Redux Saga: Need to trigger a route change after user clicks button on form

I'm working on a project that was built using Redux Saga. I have a component that features a group of offers each with their own button to select that specific offer. This component lives on page 1 of 4 and I'm trying to figure out how to trigger a redirect to the next page after the user clicks a selection, but I have no idea how to do this within the context of Redux or Redux Saga. I've included both the navigation handler and my component below. I started to edit the navigation component with a proposed action UPDATE_PAGE: but I'm not sure I'm even heading down the right path. Any suggestions/explanations or code samples on how to do this would be hugely appreciated
Offer Component
import React, { Fragment, Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Route, Switch, Redirect } from 'react-router-dom'
import styled from 'styled-components'
import NavigationContainer from '../../containers/NavigationContainer'
import RouteLoader from '../../components/core/RouteLoader'
import { getCustomer } from '../../actions/customer'
import { routerPropTypes, routePropTypes } from '../../propTypes'
class OrdersRoutes extends Component {
static propTypes = {
customer: PropTypes.object,
getCustomer: PropTypes.func.isRequired,
routes: routePropTypes,
...routerPropTypes
}
getAppData = data => {
this.props.getCustomer(data)
}
render() {
const { match, customer } = this.props
const { offers: offersRoute, ...routes } = this.props.routes
return (
<Fragment>
<Navigation>
<Route
path={match.path}
component={NavigationContainer}
/>
</Navigation>
<PageContainer>
<Switch>
<RouteLoader
exact
path={`${match.path}${offersRoute.path}`}
component={offersRoute.component}
shouldLoad={customer !== undefined}
onLoad={this.getAppData}
/>
{Object.values(routes).map(
({
path, id, component, disabled
}) =>
!disabled && (
<Route
exact
key={id}
path={`${match.path}${path}`}
component={component}
/>
)
)}
<Redirect to={`${match.path}${offersRoute.path}`} />
</Switch>
</PageContainer>
</Fragment>
)
}
}
const Navigation = styled.div`
padding: 0 10px;
`
const PageContainer = styled.div`
padding: 0 20px;
margin-top: 10px;
`
const mapStateToProps = state => ({
routes: state.navigation.pages.orders.routes,
customer: state.customer.details
})
const mapDispatchToProps = { getCustomer }
export default connect(
mapStateToProps,
mapDispatchToProps
)(OrdersRoutes)
Navigation Component
import * as pages from '../constants/pages'
export const initialState = {
pages: {
...pages
}
}
function navigationReducer(state = initialState, { type, payload }) {
switch (type) {
UPDATE_PAGE: {
const { id, page } = payload
return {
...state,
pages: {
...state.pages,
[id]: {
...state.pages[id],
...page
}
}
}
}
default: {
return state
}
}
}
export default navigationReducer
The trick is to include react-router's history into the payload of UPDATE_PAGE.
So 1) we wrap a component which triggers this action withRouter. This gives us access to history as a prop; 2) when dispatching UPDATE_PAGE, include history as a payload in addition to id and page 3) in redux-saga perform a redirect on every UPDATE_PAGE:
yield takeEvery(UPDATE_PAGE, function*(action){ action.payload.history.push('/new-route'); })

How to use Redirect in version 5 of react-router-dom of Reactjs

I am using the last version react-router module, named react-router-dom, that has become the default when developing web applications with React. I want to know how to make a redirection after a POST request. I have been making this code, but after the request, nothing happens. I review on the web, but all the data is about previous versions of the react router, and no with the last update.
Code:
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'
import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';
class SignUpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
client: {
userclient: '',
clientname: '',
clientbusinessname: '',
password: '',
confirmPassword: ''
}
};
this.processForm = this.processForm.bind(this);
this.changeClient = this.changeClient.bind(this);
}
changeClient(event) {
const field = event.target.name;
const client = this.state.client;
client[field] = event.target.value;
this.setState({
client
});
}
async processForm(event) {
event.preventDefault();
const userclient = this.state.client.userclient;
const clientname = this.state.client.clientname;
const clientbusinessname = this.state.client.clientbusinessname;
const password = this.state.client.password;
const confirmPassword = this.state.client.confirmPassword;
const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };
axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
.then((response) => {
this.setState({
errors: {}
});
<Redirect to="/"/> // Here, nothings happens
}).catch((error) => {
const errors = error.response.data.errors ? error.response.data.errors : {};
errors.summary = error.response.data.message;
this.setState({
errors
});
});
}
render() {
return (
<div className={styles.section}>
<div className={styles.container}>
<img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
<SignUpForm
onSubmit={this.processForm}
onChange={this.changeClient}
errors={this.state.errors}
client={this.state.client}
/>
<Footer />
</div>
</div>
);
}
}
export default SignUpPage;
You have to use setState to set a property that will render the <Redirect> inside your render() method.
E.g.
class MyComponent extends React.Component {
state = {
redirect: false
}
handleSubmit () {
axios.post(/**/)
.then(() => this.setState({ redirect: true }));
}
render () {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/somewhere'/>;
}
return <RenderYourForm/>;
}
You can also see an example in the official documentation: https://reacttraining.com/react-router/web/example/auth-workflow
That said, I would suggest you to put the API call inside a service or something. Then you could just use the history object to route programatically. This is how the integration with redux works.
But I guess you have your reasons to do it this way.
Here a small example as response to the title as all mentioned examples are complicated in my opinion as well as the official one.
You should know how to transpile es2015 as well as make your server able to handle the redirect. Here is a snippet for express. More info related to this can be found here.
Make sure to put this below all other routes.
const app = express();
app.use(express.static('distApp'));
/**
* Enable routing with React.
*/
app.get('*', (req, res) => {
res.sendFile(path.resolve('distApp', 'index.html'));
});
This is the .jsx file. Notice how the longest path comes first and get's more general. For the most general routes use the exact attribute.
// Relative imports
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
// Absolute imports
import YourReactComp from './YourReactComp.jsx';
const root = document.getElementById('root');
const MainPage= () => (
<div>Main Page</div>
);
const EditPage= () => (
<div>Edit Page</div>
);
const NoMatch = () => (
<p>No Match</p>
);
const RoutedApp = () => (
<BrowserRouter >
<Switch>
<Route path="/items/:id" component={EditPage} />
<Route exact path="/items" component={MainPage} />
<Route path="/yourReactComp" component={YourReactComp} />
<Route exact path="/" render={() => (<Redirect to="/items" />)} />
<Route path="*" component={NoMatch} />
</Switch>
</BrowserRouter>
);
ReactDOM.render(<RoutedApp />, root);
React Router v5 now allows you to simply redirect using history.push() thanks to the useHistory() hook:
import { useHistory } from "react-router-dom"
function HomeButton() {
let history = useHistory()
function handleClick() {
history.push("/home")
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
)
}
Simply call it inside any function you like.
this.props.history.push('/main');
Try something like this.
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'
import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';
class SignUpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
callbackResponse: null,
client: {
userclient: '',
clientname: '',
clientbusinessname: '',
password: '',
confirmPassword: ''
}
};
this.processForm = this.processForm.bind(this);
this.changeClient = this.changeClient.bind(this);
}
changeClient(event) {
const field = event.target.name;
const client = this.state.client;
client[field] = event.target.value;
this.setState({
client
});
}
processForm(event) {
event.preventDefault();
const userclient = this.state.client.userclient;
const clientname = this.state.client.clientname;
const clientbusinessname = this.state.client.clientbusinessname;
const password = this.state.client.password;
const confirmPassword = this.state.client.confirmPassword;
const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };
axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
.then((response) => {
this.setState({
callbackResponse: {response.data},
});
}).catch((error) => {
const errors = error.response.data.errors ? error.response.data.errors : {};
errors.summary = error.response.data.message;
this.setState({
errors
});
});
}
const renderMe = ()=>{
return(
this.state.callbackResponse
? <SignUpForm
onSubmit={this.processForm}
onChange={this.changeClient}
errors={this.state.errors}
client={this.state.client}
/>
: <Redirect to="/"/>
)}
render() {
return (
<div className={styles.section}>
<div className={styles.container}>
<img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
{renderMe()}
<Footer />
</div>
</div>
);
}
}
export default SignUpPage;
Update for react-router-dom v6, there is a useNavigate hook for condtional redirection and Link component
import { useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
export default function Example(): JSX.Element {
const navigate = useNavigate();
useEffect(() => {
...
if(true) { // conditional redirection
navigate('/not-found', { replace: true });
}
}, []);
return (
<>
...
<Link to="/home"> Home </Link> // relative link navigation to /home
...
</>
);
}
useNavigate
Relative Link Component
Alternatively, you can use withRouter. You can get access to the history object's properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.
import React from "react"
import PropTypes from "prop-types"
import { withRouter } from "react-router"
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return <div>You are now at {location.pathname}</div>
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
Or just:
import { withRouter } from 'react-router-dom'
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
The problem I run into is I have an existing IIS machine. I then deploy a static React app to it. When you use router, the URL that displays is actually virtual, not real. If you hit F5 it goes to IIS, not index.js, and your return will be 404 file not found. How I resolved it was simple. I have a public folder in my react app. In that public folder I created the same folder name as the virtual routing. In this folder, I have an index.html with the following code:
<script>
{
sessionStorage.setItem("redirect", "/ansible/");
location.href = "/";
}
</script>
Now what this does is for this session, I'm adding the "routing" path I want it to go. Then inside my App.js I do this (Note ... is other code but too much to put here for a demo):
import React, { Component } from "react";
import { Route, Link } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Redirect } from 'react-router';
import Ansible from "./Development/Ansible";
import Code from "./Development/Code";
import Wood from "./WoodWorking";
import "./App.css";
class App extends Component {
render() {
const redirect = sessionStorage.getItem("redirect");
if(redirect) {
sessionStorage.removeItem("redirect");
}
return (
<Router>
{redirect ?<Redirect to={redirect}/> : ""}
<div className="App">
...
<Link to="/">
<li>Home</li>
</Link>
<Link to="/dev">
<li>Development</li>
</Link>
<Link to="/wood">
<li>Wood Working</li>
</Link>
...
<Route
path="/"
exact
render={(props) => (
<Home {...props} />
)}
/>
<Route
path="/dev"
render={(props) => (
<Code {...props} />
)}
/>
<Route
path="/wood"
render={(props) => (
<Wood {...props} />
)}
/>
<Route
path="/ansible/"
exact
render={(props) => (
<Ansible {...props} checked={this.state.checked} />
)}
/>
...
</Router>
);
}
}
export default App;
Actual usage: chizl.com
EDIT: changed from localStorage to sessionStorage. sessionStorage goes away when you close the tab or browser and cannot be read by other tabs in your browser.
NOTE: Answering just the title of the question
Previous Version
<Redirect from="/old-url" to="/new-url" />
Latest version
<Route path="/old-url" element={<Navigate to="/new-url" />} />
In v6 of react-router you can accomplish this using <Navigate/> tag as there is no <Redirect/> Component.
In my case. I was required to maintain the connection to the server between /Home route and /chat route; setting window.location to something would re-render that destroys client-server connection I did this.
<div className="home-container">
{redirect && <Navigate to="/chat"/>}
<div className="home__title">
....
<div className="home__group-list" onClick={handleJoin}>
</div>
const [redirect, doRedirect] = useState(false)
handleJoin changes the state of redirect to true.
you can write a hoc for this purpose and write a method call redirect, here is the code:
import React, {useState} from 'react';
import {Redirect} from "react-router-dom";
const RedirectHoc = (WrappedComponent) => () => {
const [routName, setRoutName] = useState("");
const redirect = (to) => {
setRoutName(to);
};
if (routName) {
return <Redirect to={"/" + routName}/>
}
return (
<>
<WrappedComponent redirect={redirect}/>
</>
);
};
export default RedirectHoc;
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-router-dom": "^4.2.2"
For navigate to another page (About page in my case), I installed prop-types. Then I import it in the corresponding component.And I used this.context.router.history.push('/about').And it gets navigated.
My code is,
import React, { Component } from 'react';
import '../assets/mystyle.css';
import { Redirect } from 'react-router';
import PropTypes from 'prop-types';
export default class Header extends Component {
viewAbout() {
this.context.router.history.push('/about')
}
render() {
return (
<header className="App-header">
<div className="myapp_menu">
<input type="button" value="Home" />
<input type="button" value="Services" />
<input type="button" value="Contact" />
<input type="button" value="About" onClick={() => { this.viewAbout() }} />
</div>
</header>
)
}
}
Header.contextTypes = {
router: PropTypes.object
};
Alternatively, you can use React conditional rendering.
import { Redirect } from "react-router";
import React, { Component } from 'react';
class UserSignup extends Component {
constructor(props) {
super(props);
this.state = {
redirect: false
}
}
render() {
<React.Fragment>
{ this.state.redirect && <Redirect to="/signin" /> } // you will be redirected to signin route
}
</React.Fragment>
}
Hi if you are using react-router v-6.0.0-beta or V6 in This version Redirect Changes to Navigate like this
import { Navigate } from 'react-router-dom'; // like this CORRECT in v6
import { Redirect } from 'react-router-dom'; // like this CORRECT in v5
import { Redirect } from 'react-router-dom'; // like this WRONG in v6
// This will give you error in V6 of react-router and react-router dom
please make sure use both same version in package.json
{
"react-router": "^6.0.0-beta.0", //Like this
"react-router-dom": "^6.0.0-beta.0", // like this
}
this above things only works well in react Router Version 6
The simplest solution to navigate to another component is( Example
navigates to mails component by click on icon):
<MailIcon
onClick={ () => { this.props.history.push('/mails') } }
/>
To navigate to another component you can use this.props.history.push('/main');
import React, { Component, Fragment } from 'react'
class Example extends Component {
redirect() {
this.props.history.push('/main')
}
render() {
return (
<Fragment>
{this.redirect()}
</Fragment>
);
}
}
export default Example
I found that place to put the redirect complent of react-router is in the method render, but if you want to redirect after some validation, by example, the best way to redirect is using the old reliable, window.location.href, i.e.:
evalSuccessResponse(data){
if(data.code===200){
window.location.href = urlOneSignHome;
}else{
//TODO Something
}
}
When you are programming React Native never will need to go outside of the app, and the mechanism to open another app is completely different.

Categories