Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set useState to value inside of compent

The code sets the textCount to match the input onChange, but I need textCount to also be set to the value that comes from inside of App() from name.

import React, { useState } from "react";

function Textarea(props) {
  const [textCount, settextCount] = useState(0);

  const recalculate = (e) => {
    settextCount(e.target.value.length);
  };

  return (
    <>
      <textarea
        type="text"
        onChange={(e) => {
          recalculate(e);
          props.onChange(e);
        }}
      />
      <p>{textCount}/5</p>
    </>
  );
}
export default Textarea;
const App = (props) => {
const {name} = props.stateData;
  const change = async (e) => {
    props.changevalue(e);
  };
  return (
    <>
      <Textarea value={name} onChange={change} />
    </>
  );
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can add a state inside your Textarea component and set it to its initial value, also initialize the count corresponding:

  const [textCount, settextCount] = useState(props.value.length);
  const [textValue, setTextValue] = useState(props.value);

Then use the textvalue inside the textarea:

  <textarea
    type="text"
    value={textValue}
    onChange={(e) => {
      recalculate(e);
      props.onChange(e);
      setTextValue(e.target.value)
    }}
  />

if that is what your looking for here’s a working sandbox

Edit: add the improved sandbox from comments

improved version from @Leland

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading