Vincent Nguyen
Vincent Nguyen

Reputation: 1663

React how to access state from a function in another file?

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

Answers (1)

Kevin Raoofi
Kevin Raoofi

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:

  1. Have the parent contain the state and just pass a function to Login to have controlled access to the parent state
  2. Have Login render PrivateRoute conditionally
  3. Use Context API or some state management tool like redux so that the state is effectively global

Some 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

Related Questions