I have the component Login:
class Login extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: false
};
and want to access isAuthenticated from another file routes.js:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={() => (
Login.state.isAuthenticated === true
? <Component {...this.props}/>
: <Redirect to="/" />
)}/>
)
export default () => (
<BrowserRouter>
<div>
<Navbar />
<Switch>
<Route path="/" exact component={Login} />
<Route path="/register" exact component={Register} />
<PrivateRoute path="/home" exact component={Home} />
</Switch>
</div>
</BrowserRouter>
);
How would I go about doing this? Also what is this routes file called? Is it another "component"? Would I need to somehow pass the state from Login as props?
The gist of it is that parent component must have state as a parent cannot touch a child's state. There are several ways to achieve what you're trying to do:
Login to have controlled access to the parent stateLogin render PrivateRoute conditionallySome suggestions for 1:
class App extends React.Component {
constructor() {
super()
this.state = { isAuthenticated: false }
}
setAuthenticated = (isAuthenticated) => {
this.setState({ isAuthenticated })
}
render() {
return (
<BrowserRouter>
<div>
<Navbar />
<Switch>
<Route path="/" exact component={() =>
<Login
isAuthenticated={this.state.isAuthenticated}
setAuthenticated={this.setAuthenticated}/>}/>
<Route path="/register" exact component={Register} />
<PrivateRoute path="/home" exact component={Home} />
</Switch>
</div>
</BrowserRouter>)
}
}
And then Login would need to be altered to pull the value of isAuthenticated and use the function setAuthenticated from the props.
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