React JS: How to pass variable from one file to another file, which is not parent or child of the same?

Viewed 141
import moment from "moment";
import TrackerByDate from "./traker_by_date/tabs";

export default function Calender() {
  const [value] = useState(new Date());
  const [show, setTracker] = useState(false);

  const [dateState, setDateState] = useState(new Date());
  const changeDate = (e) => {
    setDateState(e);
  };
  var pikerdate = moment(dateState).format("YYYY-MM-DD");
  function clickTracker(e) {
    setTracker(!show);
  }

  return (
    <>
      {show ? <TrackerByDate dataFromParent={pikerdate} /> : null}
      <div style={{ width: "260px" }} className="res-calendar">
        <Calendar
          className={["c1", "c2"]}
          onChange={changeDate}
          onClickDay={clickTracker}
          value={dateState}
        />
      </div>
    </>
  );

I am trying to pass 'pikerdate' to a js file called diet. callander.js and diet.js are not parent or child

I want to get a date in diet.js when the date is clicked on callender.js

2 Answers

To provide the best answer here we need to consider the relationship between both components.

For instance, if both components are ultimately rendered by a single parent component, then a simple and convenient way to manage this would be to simply move the state to the parent and pass it as props to the child components along with the setState method or dedicated functions to handle the relevant logic.

Example:

function Parent() {
   const [state, setState] = useState();

   return (
      <A state={state} setState={setState} />
      <B state={state} setState={setState} />
   )
}

However, if that is not the case and the relationship between them is more complex,
then you likely need to manage some global state.
This can be achieved via React's built-in Context Api or via third party state managment libraries such as Redux or xState.

you can do it by taking "pikerdate" in the parent component where there two components(called and diet) are children like in App.js or some other component and pass "pikerdate" to both components.

Related