0

I want to insert via URL some data like an ID.

Example: somewebsite.com/movie/(ID_GOES_HERE)

But i can't understand how to make it happen. I want the data to go in the url and i want to retrieve it in movie.js, how do i do that?

I installed router dom in the app.

import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Switch, Route} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import App from './App';
import MovieDetail from './Movie';

const history = createBrowserHistory();

ReactDOM.render(
  <Router history={history}>
    <Switch>
      <Route exact path='/' component={App}/>
      <Route path='/movie' component={Movie}/>
    </Switch>
  </Router>,
       document.getElementById('root')
);

It is expected to show the ID in Movie.

user ct
  • 47
  • 6

1 Answers1

1

From react-router documentation:

./App

<Route path="/movie/:movie_id" component={Movie} />;

./Movie

// All route props (match, location and history) are available to Movie
export function Movie(props) {
  return <h1>Show movie {props.match.params.movie_id}!</h1>;
}
Corey
  • 5,818
  • 2
  • 24
  • 37
  • The function should be in the same index.js (routes) file? How will Movie.js receive the parameter data? – user ct Jul 31 '19 at 15:34
  • No, as you have it will work. When you pass a component to a `Route` with `react-router-dom`, that component will automatically receive props (match, location, and history) from the router context. – Corey Jul 31 '19 at 15:37
  • I did it and it throws " Line 5: Parsing error: Unexpected token" which corresponds to: "export function Movie(props) {" – user ct Jul 31 '19 at 18:22
  • The snippet for `Movie` is just a generic representation of a React component. In this case, a functional component. Yours may very well be a class component. The only part that would be relevant to your case would be `props.match.params.movie_id`. If it's a class component, it would likely be `this.props.match.params.movie_id`. – Corey Jul 31 '19 at 19:16