reactjstypescriptnext.jsnextui

How to use multiple useInput in a component?


Introduction: I'm new to web development, I come from mobile. I have two Textareas in a page to build a text article, which I need to reset after submit.

Problem:

import { useInput } from "@nextui-org/react"
const {
  value: controlledValue,
  setValue: setControlledValue,
  reset,
  bindings,
} = useInput("");

const {
  value: controlledValue,
  setValue: setControlledValue,
  reset,
  bindings,
} = useInput("")

I'm trying to use two useInputs hooks, one for the article title and the second for the article body. I have tried many ways to reset the Texture but I can't. I see that with this hook "useInput" it works. The problem is that I can't rename the values of that hook and then they are duplicated.

Please is there a way to use this hook for multiple values?

I'm on NextJS 13.0 / NextUI and using TypeScript.


Solution

  • You can rename values returned from the hook as follows:

    "use client";
    
    import * as React from "react";
    import { useInput } from "@nextui-org/react";
    
    export default function Home() {
      const { reset: reset1, bindings: bindings1 } = useInput("");
      const { reset: reset2, bindings: bindings2 } = useInput("");
    
      const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
    
        const data = new FormData(event.target as HTMLFormElement);
    
        const textarea1 = data.get("textarea1");
        const textarea2 = data.get("textarea2");
    
        // ...
    
        reset1();
        reset2();
      };
    
      return (
        <form onSubmit={onSubmit}>
          <textarea name="textarea1" {...bindings1} />
          <textarea name="textarea2" {...bindings2} />
          <button type="submit">Submit</button>
        </form>
      );
    }