score:113

Accepted answer

how about writing a reusable function that returns the input value ... and the <input> itself:

 function useinput({ type /*...*/ }) {
   const [value, setvalue] = usestate("");
   const input = <input value={value} onchange={e => setvalue(e.target.value)} type={type} />;
   return [value, input];
 }

that can then be used as:

 const [username, userinput] = useinput({ type: "text" });
 const [password, passwordinput] = useinput({ type: "text" });

 return <>
   {userinput} -> {username} <br />
   {passwordinput} -> {password}
 </>;

score:0

you may want to consider a form library like formik

score:3

here's how i do it (assuming your inputs must be inside a form):

i have a basicform component that i use.

it stores all the inputs state into an object into a single usestate() call.

it passes via usecontext() the inputs state along with an onchange() function and a function setinputinitialstate() for the inputs to set their initial state when they are first mounted. it also passes onfocus, onblur, and it has functions to validate fields which i'm not showing here to simplify the code.

this way i can easily create a form with as many inputs as i want, like:

<basicform
      issubmitting={props.issubmitting}
      submitaction={ (formstate) =>
        props.dosignin(formstate) }
    >
      <textinput
        type='email'
        label='email'
        name='email'
        placeholder='enter email...'
        required
      />
      <textinput
        type='password'
        label='password'
        name='password'
        placeholder='enter password...'
        min={6}
        max={12}
        required
      />
      <submitbutton
        label='login'
      />
    </basicform>

basicform.js

import formcontext from './parts/formcontext';

function basicform(props) {

  const [inputs, setinputs] = usestate({});

  function onchange(event) {
    const newvalue = event.target.value;
    const inputname = event.target.name;
    setinputs((prevstate)=> {
      return({
        ...prevstate,
        [inputname]: {
          ...prevstate[inputname],
          value: newvalue,
          dirty: true
        }
      });
    });
  }

  function setinputinitialstate(
    inputname,
    label='this field ',
    type,
    initialvalue = '',
    min = false,
    max = false,
    required = false) {

    const initial_input_state = {
      label: label,
      type: type,
      onfocus: false,
      touched: false,
      dirty: false,
      valid: false,
      invalid: false,
      invalidmsg: null,
      value: initialvalue,
      min: min,
      max: max,
      required: required
    };

    setinputs((prevstate) => {
      if (inputname in prevstate) {
        return prevstate;
      }
      return({
        ...prevstate,
        [inputname]: initial_input_state
      });
    });

  }

return(
    <formcontext.provider value={{
      onchange: onchange,
      inputs: inputs,
      setinputinitialstate: setinputinitialstate,
    }}>
      <form onsubmit={onsubmit} method='post' novalidate>
        {props.children}
      </form>
    </formcontext.provider>
  );
}

textinput.js

the inputse use the useeffect() hook to set their initial state when they're mounted.

function textinput(props) {

  const formcontext = usecontext(formcontext);

  useeffect(() => {
    console.log('textinput useeffect...');
    formcontext.setinputinitialstate(
      props.name,
      props.label,
      props.type,
      props.initialvalue,
      props.min,
      props.max,
      props.required
    );
  },[]);

  return(
      <input
        type={props.type}
        id={props.name}
        name={props.name}
        placeholder={props.placeholder}
        value={([props.name] in formcontext.inputs) ?
                  formcontext.inputs[props.name].value
                : props.initialvalue || ''}
        onchange={formcontext.onchange}
        onfocus={formcontext.onfocus}
        onblur={formcontext.onblur}
      >
      </input>
      </div>
      {([props.name] in formcontext.inputs) ?
          formcontext.inputs[props.name].invalidmsg && <div><span> {formcontext.inputs[props.name].invalidmsg}</span></div>
        : null}
    </div>
  );

...
}

score:3

function app(){
    const [name, setname] = usestate("");
    const [istrue, setistrue] = usestate(false);
    const [lastname,setlastname]=usestate("");
    
    function handleclick(){
       setistrue(true);
    }
    
    return(
        <div>
            {istrue ? <div> <h1>{name} {lastname}</h1> </div> : 
            <div>
                <input type="text" placeholder="firstname" name="name" onchange={e =>setname(e.target.value)}/>
                <input type="text" placeholder="lastname" name="lastname" onchange={e =>setlastname(e.target.value)}/>
               <button  type="submit" onclick={handleclick}>submit</button>
            </div>}
        </div>
    )
    
    }

}

score:37

this is how i'm using right now:

const [inputvalue, setinputvalue] = react.usestate("");

const onchangehandler = event => {
   setinputvalue(event.target.value);
};

<input
   type="text"
   name="name"
   onchange={onchangehandler}
   value={inputvalue}
/>

score:39

yes you can handle react hooks with usestate()

import react, {usestate} from 'react'

export default () => {
    const [fname, setfname] = usestate('');
    const [lname, setlname] = usestate('');
    const [phone, setphone] = usestate('');
    const [email, setemail] = usestate('');

const submitvalue = () => {
    const frmdetails = {
        'first name' : fname,
        'last name' : lname,
        'phone' : phone,
        'email' : email
    }
    console.log(frmdetails);
}

return(
    <>
    <hr/>
    <input type="text" placeholder="first name" onchange={e => setfname(e.target.value)} />
    <input type="text" placeholder="last name" onchange={e => setlname(e.target.value)} />
    <input type="text" placeholder="phone" onchange={e => setphone(e.target.value)} />
    <input type="text" placeholder="email" onchange={e => setemail(e.target.value)} />
    <button onclick={submitvalue}>submit</button>
    </>
    )
}

Related Query

More Query from same tag