1

I'm trying to pass state from one page to another and am running into problems.

Page 1

<Link to={'/events'}  state={{ id: "Check" }}>
  Check
</Link>

Page 2 - Events

export class Events extends Component {
  render() {
    return (
      <div>
        <h1>Events Page</h1>
      </div>
    );
  }
}

export default function page(props) {
  const location = useLocation();
  return (
    <div>
      <h1>{this.props.location.state.id}</h1>
    </div>
  );
}

I'm getting the following errors:

React Hook "useLocation" is called in function "page" that is neither a React function component nor a custom React Hook function.

Parameter 'props' implicitly has an 'any' type.

45 | export default function page(props) {

'this' implicitly has type 'any' because it does not have a type annotation.

49 | {this.props.location.state.id}

I've tried multiple methods and I am struggling to get anything to compile. I'm very new to React and I am just missing something. There seems to be a difference between V5 and V6 react-router which is tripping me up (Using V6).

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
C-Bertram
  • 79
  • 6

1 Answers1

0

React components are Capitalized. page is interpreted to be just a regular Javascript function that just happens to return valid JSX, but it isn't a React component. Additionally, React function components are instance-less, this is simply undefined. I'm certain you meant to access location.state.id in the render return.

You should also note that location.state is potentially undefined if a user navigates directly to a route that renders the Page component and thus no state was passed via the Link component. The component should do a null-check prior to accessing into the location.state property. The Optional Chaining operator is one method for doing this.

You can likely also remove the props object/reference since it isn't referenced in the function body.

export default function Page() {
  const location = useLocation();
  return (
    <div>
      <h1>{location.state?.id}</h1>
    </div>
  );
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Ok, this makes sense. It's still not quite working as expected as it only renders whats in the `export class Events extends Component` but I can't use the `useLocation` within the class method as I'm getting the error `react hook uselocation cannot be called in a class component` I'm missing something here to pass the states from one page to the other. – C-Bertram Feb 22 '23 at 00:02
  • 1
    @C-Bertram If you are still using React Class-based components then you'll need to either convert to React Function components or roll your own [withRouter](https://reactrouter.com/en/main/start/faq#what-happened-to-withrouter-i-need-it) Higher Order Component in order to use the React hooks. https://stackoverflow.com/a/64816926/8690857 – Drew Reese Feb 22 '23 at 00:04