-1

I simply want to use a data that has been calculated in a child component and also use the same data in my parent component. How do i do so? This is my current approach, it works but i get this error:

Cannot update a component from inside the function body of a different component

Please suggest a correct method.

Parent:


const Parent = () => {
  const [myValue, setMyValue] = useState("");
  const getValue = (value) => {
    setMyValue(value);
  };

  return (
      <div className={styles.innerContainer}>
        <div className={styles.introPara}>{myValue}</div>
        <Child passToParent={getValue} />
      </div>

  );
};

export default Parent;

Child

const Child = ({ passToParent }) => {
  let url = "www.google.com";
  const findUrl = () => {
    return url;
  };
  let finalValue = findUrl();
  const finalText = finalValue.toUpperCase();

  passToParent(finalText);

  return (
    <div>
      <a href={finalValue}>
        <div>{finalText}</div>
      </a>
    </div>
  );
};

export default Child;

I want to use the finalText in both Child and Parent components but i don't want to repeat the logic i'm using in finalUrl( ). Currently i'm simply using passToParent( ) and it works but gives error.

James Z
  • 12,209
  • 10
  • 24
  • 44
zigaish
  • 68
  • 1
  • 7

1 Answers1

-1

try this - just pass myValue - instead getFunction:


  1. getValue - this is the function - it's should be triggered on some user actions eg. onClick, onMouseEnter etc.

  2. You hold myValue in useState reactHook - it's type: string

  3. In child u destructurizing props - so there is option just to write it without processing.

  4. Also there is possibility to pass function to child component


const Parent = () => {
  const [myValue, setMyValue] = useState("");

  const getValue = (value) => {
    setMyValue(value);
  };

  return (
      <div>
        <Child passToParent={myValue} />
      </div>

  );
};

export default Parent;

const Child = ({ passToParent }) => {

  return (
    <div>
      <a>
        <div>{passToParent}</div>
      </a>
    </div>
  );
};

export default Child;
Piotr Żak
  • 2,046
  • 5
  • 18
  • 30