Ad

Live Updates Between React Components Based On State

- 1 answer

My (simplified) goal:
Show a form input's text content beside the form itself and update the reflected text as the input text changes. The form lives within a React component, and the displayed text lives inside another one.

I can use the component state to control the input's text and change the state based on onChange form event. But how can I also change the state of the displayed text so that I get the live updates I'm looking for?

Input and output components have the same parent component.

Here's my input component:

import React, { useState } from "react";

function InputBoxTest() {
  const [inText, setInText] = useState("");

  const handleChange = event => {
    setInText(event.target.value);
    // My instinct is to setOutText here, but I can't...
  };

  return (
    <textarea className="form-control" id="comment" onChange={handleChange}>
      {inText}
    </textarea>
  );
}

export default InputBoxTest;

My output component:

import React, { useState } from "react";

function OutputBoxTest() {
  const [outText, setOutText] = useState("");

  return <p>{outText}</p>;
}

export default OutputBoxTest;

And my parent component:

import React from "react";
import InputBoxTest from "./InputBoxTest";
import OutputBoxTest from "./OutputBoxTest";

function Test1(props) {
  return (
    <>
      <div className="row">
        <div className="container-fluid col-sm-7">
          <InputBoxTest />
        </div>
        <div className="col-sm-5">
          <OutputBoxTest />
        </div>
      </div>
    </>
  );
}

export default Test1;
Ad

Answer

You could move the State Hook from InputBoxText into the ParentComponent Test1 InputBoxText is then used for displaying and updating the state OutputBoxText is used for displaying only

import React from "react";
import InputBoxTest from "./InputBoxTest";
import OutputBoxTest from "./OutputBoxTest";

function Test1(props) {

   const [inText, setInText] = useState("");
   const handleChange = event => {
       setInText(event.target.value);
   };

   return (
      <>
         <div className="row">
         <div className="container-fluid col-sm-7">
             <InputBoxTest text={inText} handleChange={handleChange}  />
         </div>
         <div className="col-sm-5">
            <OutputBoxTest text={inText}/>
         </div>
        </div>
     </>
   );
}

export default Test1;


function InputBoxTest(props) {
   return (
      <textarea className="form-control" id="comment" onChange={props.handleChange}>
         {props.text}
      </textarea>
   );
}
export default InputBoxTest;


function OutputBoxTest(props) {
   return <p>{props.text}</p>;
}

 export default OutputBoxTest;
Ad
source: stackoverflow.com
Ad