Home > other >  React - run onChange for multiple inputs
React - run onChange for multiple inputs

Time:11-19

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

CodePudding user response:

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

  • Related