0

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

1
  • That means you are not properly sending the params to the ResetPassword component, so when the component mounts there is no params. Check how you are setting the :token as the error is coming from there Commented Jan 17, 2021 at 16:17

2 Answers 2

1

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

import { useParams } from "react-router";
const { token } = useParams();
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.