Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Pass parameter from rails to react router to component

I am trying to pass a value from the render function to the component:

= react_component('App', props: {test: 'abc'}, prerender: false)

Routes.jsx

<Route path="/" component={App} >

App.jsx (component)

class App extends React.Component {
  render() {
    return (
      <Header test={this.props.test}>
      </Header>
      {this.props.children}
      <Footer />
    );
  }
}

App.propTypes = { test: PropTypes.string };

There does not seem to be a coherent answer to this complete flow.

I have tried the following:

<Route path="/" component={() => (<App myProp="value" />)}/>

But this still does not answer the question of picking up the value provided by the initial render call(react_component)

like image 418
Alex Jose Avatar asked Nov 14 '17 22:11

Alex Jose


People also ask

How do you pass parameters in route react?

Pass params to a route by putting them in an object as a second parameter to the navigation. navigate function: navigation. navigate('RouteName', { /* params go here */ }) Read the params in your screen component: route.

How do I pass data from one page to another in react router?

You can use the Link component from react-router and specify to={} as an object where you specify pathname as the route to go to. Then add a variable e.g. data to hold the value you want to pass on.

What is @param in react?

React parameters are used in React routing, where we have parameters we need to access in the route. For example, if we had a route such as <Route path=”/:id” /> we could access that particular string or value in the route by calling the useParams hook. let { id } = useParams();


2 Answers

Looking for an end to end answer on how to pass a parameter from the "view" to the "react router" to the "component"

We will start from the view:

<%= react_component('MyRoute', {test: 123}, prerender: false) %>

Now we will create a component that holds our route:

class MyRoute extends Component{
  constructor(props){
    super(props)
  }
  render(){
    return(
      <Switch>
        <Route path="/" render={() => <App test={this.props.test} />} />
        <Route path="/login" component={Login} />
      </Switch>
    )
  }
}

As you can see, we passed the test prop from the Route component to the App component. Now we can use the test prop in the App component:

class App extends Component{
  constructor(props){
    super(props)
  }
  render(){
    return(
      <h1>{this.props.test}</h1>
    )
  }
}
like image 166
Josan Iracheta Avatar answered Oct 15 '22 11:10

Josan Iracheta


<Route path="/" render={attr => <App {...attr} test="abc" />} />
like image 45
syaku Avatar answered Oct 15 '22 10:10

syaku