2
<TabPanel>
  <Dietracker dataFromParent={date} />
  <Link to="/cdiet">
    <button onClick={this.closeTabBox}>edit</button>
  </Link>
</TabPanel>

I am trying to pass dataFromParent={date} to <CDietOverview /> in navigator.js when the edit button is clicked without changing the path

<Route path="/cdiet">
  <CDietOverview />
</Route>

this is the CDietOverview file how show the date in this file ' const { date } = this.props.location.state' i thried like this but error says TypeError: Cannot read properties of undefined (reading 'state')


import React from "react";
import axios from "axios";
import Sidebar from "../components/sidebar";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBell, faUser, faBars } from "@fortawesome/free-solid-svg-icons";
import Toggler from "../toggle";
import { useLocation } from "react-router-dom";
import ClientProfile from "../tog_profile";
//import DailyTrackerTabs from './components/daily_tracker';
import DietTrackerTabs from "../components/diet_tracker_tabs";
import Calendar from "../components/calendar";
import Experts from "../components/experts";
import Greet from "../components/greet";

export default class Overview extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isToggleOn: true, isProfile: true, items: [] };
    this.handleClick = this.handleClick.bind(this);
    this.setWrap = this.setWrap.bind(this);
    this.clickedOutside = this.clickedOutside.bind(this);
    this.profileHandler = this.profileHandler.bind(this);
    if(props.location.state)
  
    const { date } = props.location.state;
    console.log(date);
 
  }
 

  componentDidMount() {
    const { date } = this.props.location.state;

    const config = {
      headers: {
        Authorization: `token ` + localStorage.getItem("token"),
      },
    };

    axios
      .get(
        "url",
        config
      )
      .then((res) => {
        console.log(res.data);
        this.setState({ items: res.data });
      });
  }

  render() {
    function openMenu() {
      document.querySelector(".sidebar").classList.toggle("show");
    }

    return (
      <div className="App">
        <Sidebar />
        <header className="overview">
          <div
            className="top-header"
            ref={this.setWrap}
            style={{ padding: "2% 10%", textAlign: "right" }}
          >
            {" "}
            <div>{this.state.isToggleOn ? null : <Toggler />}</div>
            <span>
              <FontAwesomeIcon
                onClick={this.handleClick}
                style={{ marginRight: "1rem", cursor: "pointer" }}
                icon={faBell}
              />
            </span>
            <span>
              <FontAwesomeIcon
                onClick={this.profileHandler}
                style={{ cursor: "pointer" }}
                icon={faUser}
              />
            </span>{" "}
            {this.state.items.firstname} {this.props.childern}
            {this.state.isProfile ? null : <ClientProfile />}{" "}
          </div>

          <div style={{ width: "89%", display: "flex", paddingLeft: "10px" }}>
            <span onClick={openMenu} className="menu">
              <FontAwesomeIcon
                style={{ marginRight: "20px" }}
                icon={faBars}
                className="menu-icon"
              />
            </span>
            <span style={{ whiteSpace: "nowrap" }}>Daily Tracker</span>
            <div style={{ padding: "4px", width: "100%" }}>
              <hr style={{ background: "white", color: "white" }} />
            </div>
          </div>
          <div className="mwrapper">
            <div className="mleft">
              <Greet />
              <DietTrackerTabs />
            </div>
            <div className="mright">
              <Calendar />
              <div
                style={{
                  fontWeight: "bold",
                  textAlign: "left",
                  paddingLeft: "10px",
                }}
              >
                <small style={{ textTransform: "uppercase" }}>Experts</small>
              </div>
              <Experts />
            </div>
          </div>
        </header>
      </div>
    );
  }
}

this is the CDietOverview file im getting

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
vivek kn
  • 107
  • 1
  • 18
  • 45
  • What routing/navigation library/package are you using in your project? It *looks* like `react-router-dom` but I won't make assumptions. What sort of component is `CDietOverview`? Can you include the `CDietOverview` component code in your question? – Drew Reese Sep 24 '21 at 09:16
  • i have added the code pls help – vivek kn Sep 24 '21 at 09:47
  • Your class component is named 'Overview' but you are referring to ''CDietOverview"? – Aayush Sep 24 '21 at 10:42

3 Answers3

2

You can pass parameters with Link:

<Link to={{
           pathname: '/cdiet',
           state: {date}
          }}
>
  <button onClick={this.closeTabBox}>edit</button>
</Link>

In CDietOverview:

const {date} = props.location.state;
elirand5
  • 231
  • 1
  • 7
1

Passing data with Link

<Link 
  to = {{
          pathname: `/{path}/${item}`,
          state: {Data}
       }}
>Text or Button</Link>

Retrieve data i.e. passed through link

let retrieve_var = props.location.state
0

Pass the data in route state via the Link.

<Link
  to={{
    pathname: "/cdiet",
    state: {
      date,
    },
  }}
>
  <button onClick={this.closeTabBox}>edit</button>
</Link>

Then to access the route state on the receiving component access the location object.

props.location.state.date

The issue from here though is that CDietOverview isn't receiving route props so it can't access a location prop:

<Route path="/cdiet">
  <CDietOverview /> // <-- route props not passed
</Route>

To remedy CDietOverview not receiving the route props:

  1. Render CDietOverview via the render, component, or children prop of the Route component. See Route render methods.

    <Route path="/cdiet" component={CDietOverview} />
    
  2. Use the withrouter Higher Order Component to have the route props injected as props from the closest Router context in the ReactTree. Decorate the CDietOverview component with the withRouter HOC so it will have a location prop to access.

    import { withRouter } from 'react-router-dom';
    
    ...
    
    class Overview extends React.Component {
      ...
    
      componentDidMount() {
        // access location prop
        const { date } = this.props.location.state;
        ...
      }
    
      ...
    }
    
    export default withRouter(Overview);
    
Drew Reese
  • 165,259
  • 14
  • 153
  • 181