howranwin
howranwin

Reputation: 164

How to get parameter from url in react js?

I'm very new to react and am having trouble accessing the parameter from URL. I've looked for many solutions but I kept getting the same error of "Uncaught TypeError: Cannot read property 'params' of undefined". How can I access the param from url in reactjs component?

In App.js

render() {
  return (
    <Router>
      <ResetPassword path="/reset-password/:token" />
    </Router>
  )
}

In ResetPassword.js

import React, { Component } from "react";

class ResetPassword extends Component {
  componentDidMount() {
    const { token } = this.props.match.params.token;
    console.log(token);
  }

  render() {
    return (
      <div className="resetPassword">
        <div className="change__container">
          <form>
            <h1 id="changePassword__message"></h1>
            <input
              type="password"
              name="password"
              placeholder="password"
              className="change__textInput"
              required
            />
            <input
              type="password"
              name="passwordTwo"
              placeholder="confirm password"
              className="change__textInput"
              required
            />
            <input type="submit" value="Submit" className="change__btnInput btn" required />
          </form>
        </div>
      </div>
    );
  }
}

export default ResetPassword;

Error Uncaught TypeError: Cannot read property 'params' of undefined

Upvotes: 0

Views: 625

Answers (2)

Salehi
Salehi

Reputation: 221

you should add component as prop to access match

import { Route } from "react-router-dom";

<Route
 path="/reset-password/:token"
 component={ResetPassword}
/>

or if you want pass custom props you can use render prop:

<Route
 path="/reset-password/:token"
 render={(props) => <ResetPassword {...props} myProp={"foo"} />}
/>

And for reading token you can do one of these ways:

const { token } = this.props.match.params;
const token = this.props.match.params.token;

Upvotes: 0

Mihai Moraru
Mihai Moraru

Reputation: 404

Assuming that you use react-router, you may try this:

import { useParams } from "react-router";
const { token } = useParams();

Upvotes: 1

Related Questions