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

React – run onChange for multiple inputs

I am trying to run the recalculate function separately for every input but it runs simultaneously instead of individually. How do I change the code to run for each separate instance of the inputs?

   export default function FullWidthTabs() {
      const [textAreaCount, ChangeTextAreaCount] = React.useState(0);
    
      const recalculate = (e) => {
        ChangeTextAreaCount(e.target.value.length);
      };

      return (
        <div>
          <p>{textAreaCount}/5</p>
          <textarea type="text" rows={5} maxLength={5} onChange={recalculate} />
    
          <p>{textAreaCount}/5</p>
          <textarea type="text" rows={5} maxLength={5} onChange={recalculate} />
        </div>
      );
    }

https://codesandbox.io/s/rkv88-forked-e66hkd

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

>Solution :

I want to be able to have the counter run per . Right now when I type in one textarea, both counters run at the same time

I believe the best approach for this would be to just make every textarea as a separate, reusable component with it’s own state.

const Textarea = () => {
  const [textAreaCount, ChangeTextAreaCount] = React.useState(0);

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

  return (
    <>
      <p>{textAreaCount}/5</p>
      <textarea type="text" rows={5} maxLength={5} onChange={recalculate} />
    </>
  );
};

export default function FullWidthTabs() {
  return (
    <div>
      <Textarea />

      <Textarea />
    </div>
  );
}

https://codesandbox.io/s/rkv88-forked-cvmkq3?file=/src/App.js:27-467

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