Using packages
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
authState: null,
};
}
mutateAuthState = () => {
this.setState({
authState: true,
});
}
render() {
return (<Routes authState={this.state.authState} mutateAuthState={this.mutateAuthState} />)
}
}
Routes.js
class Routes extends React.Component {
render() {
return (
<React.Fragment>
<BrowserRouter >
<Switch>
<Route path="/login" exact render={ () => <Login authState={this.props.authState}
mutateAuthState={this.props.mutateAuthState}/>
} />
<Route path="/" exact render={ () => <div><a href="/login" >login</a></div> } />
</Switch>
</BrowserRouter>
</React.Fragment>
);
}
}
Login.js
class Login extends Component {
handleSubmit = async (event) => {
this.props.mutateAuthState(true)
}
render() {
switch(this.props.authState) {
case true : return (<Redirect to="\" />)
default : return(
<button onClick={this.handleSubmit} >Login </button>
)
}
}
}
End result wanted - Clicking Login Button in Login.js will set the state variable authState in App.js to true.
App will rerender Routes.js since state has changed.
Inside Routes, since the url is still /login , Login component is rendered.
Inside Login, since this.props.authState is now set to true, a redirect to "/" occures.
But I am getting a DOMException in Web Console
Error: DOMException: Failed to execute 'replaceState' on 'History': A history state object with URL 'http:' cannot be created in a document with origin 'http://localhost:3000' and URL 'http://localhost:3000/login'.
Is this the proper architecture for Authentication in React?
Two things that I can see.
Shouldn't you be redirecting to forward slash and not backslash?
aka change <Redirect to="\" />
to <Redirect to="/" />
Second thing is you probably need to upgrade your version of react-router. The issue is your redirect is trying to go back to home, but there is a bug when redirecting to the /
route.
Version 4.6.1
should correctly redirect for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With