Navigate to other page with props in React JS

Viewed 3666

I want to redirect from one page to other and pass props along with it. But i dont want these params in url.

Method :

   saveForLater(){
    if (typeof window !== "undefined") {
      window.location.href = "./DataDisplay/";
    }
  };

I checked with urlparams we can set {"id":content} in url. But i do not wish to pass data in url.

I can not use Link / Route in the method . Is there any way to do it/any library to checkout? Pls suggest

CODE SAMPLE:

import React, { Component } from "react";
class DATAFETCH extends Component {
  constructor(props) {
    super(props);
    this.state = {
             Attachments: [],
             validated: false,
             isDoctor:false,
    }

saveForLater(){
    if (typeof window !== "undefined") {
      window.location.href = "./DataDisplay/";
    }
  };

  render() {
    return (

              /////// Various Fields

      <Button
       onClick={() => props.submit()}
       >
)}
2 Answers

I think you've not quite understood how react works. Both Link and Route are components, so they can only be used & rendered within the render lifecycle function of a class-based component or return of a functional component. Outside of this the pattern to navigate to other routes is to use the history object to push to another route/path.

history.push('/DataDisplay');

If you need to send extraneous data along with the route push, you can use route state.

history.push({
  pathname: '/DataDisplay',
  state: {
    // any values/objects/etc you want to also send to pushed route/path
  },
});

Route state is accessed via the location object of route-props.

const { /* values/objects/etc */ } = props.location.state;

The route-props are only accessible via a component directly rendered by a Route, or by using the withRouter Higher Order Component or in the case of functional components using react hooks.

Your example code

import React, { Component } from "react";
import { withRouter } from 'react-router-dom'; // <-- import withRouter HOC

class DATAFETCH extends Component {
  ...

  saveForLater(){
    history.push({
      pathname: '/DataDisplay',
      state: {
        id: content // <-- pass in content to key `id`
      },
    });
  };

  render() {
    ...
  }
}

export default withRouter(DATAFETCH); // <-- decorate with withRouter HOC

To access on resultant route's component

props.location.state.id

Maybe you can use a store manager like the API Context. Or one alternative like MobX or Redux.

Related