0

In my React app, I use component to wrap the authentication required routes. As explained in this answer, I assigned userInfo as a user prop to each and every child as follows.

const RequireAuth = props => {

    const [userInfo,setUserInfo] = useState([])

    useEffect( () => {
            Axios.get('/users/me').then(res => {
                    setUserInfo(res.data)
                    console.log(userInfo)
            }).catch(e => {
                console.log(e)
            })
        }
    })

    const childrenWithProps = React.Children.map(props.children, child =>
        React.cloneElement(child, { user: userInfo })
      );

    return isAuth  ? (
            <div>
            {childrenWithProps}
        </div>
        ) : 
       (<ClipLoader
        size={120}
        color={"#123abc"}
        loading={loading}
      />
        )
};

export default withRouter(RequireAuth)

I wrap the auth required routes with RequireAuth as follows in App.js.

<RequireAuth>
    <Route exact path="/courses"  component={Courses}></Route>
        <Route exact path="/courses/:courseId" component={Course}></Route>
</RequireAuth>

My question is: How can I access user in Course component?

Pavindu
  • 2,684
  • 6
  • 44
  • 77
  • Inside **Course** Component `props.user`? – keikai Apr 05 '20 at 07:08
  • 1
    Instead of managing `user` with state inside `RequireAuth`, you should go with Redux to do that. After that, a simple connect from `Course` to store will give you `user` info. You can access it in `Course` props. – Cam Song Apr 05 '20 at 07:16

1 Answers1

0

You can pass user info like this:

<Route exact path="/courses/:courseId"
    render={() => <Course user={this.state.user} />}
/>