Reputation: 1663
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
?
Upvotes: 3
Views: 6450
Reputation: 1033
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.
Upvotes: 3