Ilja Ilja - 1 month ago 19
React JSX Question

Passing custom parameters to react-router onEnter function

Usually on enter functions for react-router route looks somewhat simmilar to this:

const isLoggedIn = (nextState, replace, callback) => {
/* Some checks / redirects here */
}


and we use it in Route like so

<Route onEnter={isLoggedIn} />


I was trying to pass a custom parameter, but had no luck, essentially I want to acheive something like this

<Route onEnter={isLoggedIn(myParam)} />


And be able to access it in function, so

const isLoggedIn = (myParam, nextState, replace, callback) => {
/* Some checks / redirects here */
}

Answer

You can do this using context binding. When you call the function from within React Router just bind the data you need in your auth function. You can pass over objects this way as well. Your code would look like:

function requireAuth(nextState, replace) {
   console.log(this.loggedIn)
}

<Route onEnter={requireAuth.bind({"loggeIn":this.props.loggedIn})} />

Another option would be using the function parameter, if you use ECMAScript 6:

var requireAuth=(loggedIn)=>{
   return (nextState,replace)=>{
     console.log(loggedIn)
   }
}

<Route onEnter={requireAuth(this.props.loggedIn)} />

It should work even shorter:

var requireAuth=(loggedIn)=>(nextState,replace)=>{
     console.log(loggedIn)
}

<Route onEnter={requireAuth(this.props.loggedIn)} />