Search code examples
javascriptreactjsreact-props

How to use props.match.params?


I am passing a videoId from Dashboard to URL path and fetching it in Videoplayer Component using props.match.params.videoId. If I use VideoPlayerContainer in App.js route I get error TypeError: Cannot read property 'params' of undefined but if I use VideoPlayer component instead of container in App.js route it works and gets the videoId from URL.

Any Idea how to make it work with using VideoPlayerContainer?

App.js

function App() {
      return (
        <React.Fragment>
          <Switch>
        <ProtectedRoute
          exact
          path="/dashboard"
          component={DashboardContainer}
        />
            <ProtectedRoute
              exact
              path="/videoplayer/:videoId"
              component={VideoPlayerContainer}
            />
          </Switch>
        </React.Fragment>
      );
    }
    export default App;

 

VideoPlayerContainer

    export default function VideoPlayerContainer() {
  return (
    <React.Fragment>
      <div>
        <PublicNav />
        <VideoPlayer />
      </div>
    </React.Fragment>
  );
}  

VideoPlayer

    export default function VideoPlayer(props) {
  const classes = useStyles();
  let videoId = props.match.params.videoId;
  const [video, setVideo] = useState([]);
  const [CommentLists, setCommentLists] = useState([]);

  const videoVariable = {
    videoId: videoId,
  };

Solution

  • Just pass match param that you are getting through react-router in VideoPlayerContainer to your VideoPlayer component. The below code should work

    export default function VideoPlayerContainer(props) {
      return (
        <React.Fragment>
          <div>
            <PublicNav />
            <VideoPlayer match={props.match} />
          </div>
        </React.Fragment>
      );
    }