score:113
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>
</>
)
}
Source: stackoverflow.com
Related Query
- Handle an input with React hooks
- How Can I create a Handle an input object with React hooks
- Facing a problem while Handle an input with React hooks
- Thousand separator input with React Hooks
- How to handle React Svg Drag and Drop with React Hooks
- React - handle change of input with state rendered by iteration through an array
- Properly handle multiple files input with Formik and React
- How to test a handle function call with a react functional component with hooks
- Make focus and blur input with react hooks
- how to handle multiple input changes with only 1 handler with hooks
- Get input value with react hooks to search on oMdb api
- How to use Modals with input in react hooks
- Clearing Input after submit With react hooks
- MaterialUI Text Field input getting 'undefined' values with React Hooks
- How to Sort Form Input Automatically With React Hooks
- Controlled/uncontrolled input field with React Hooks
- Handle multiple input values with React Redux Toolkit
- React Hooks useState() with Object
- React input defaultValue doesn't update with state
- React Function Components with hooks vs Class Components
- Reset to Initial State with React Hooks
- Wrong React hooks behaviour with event listener
- Why can't I change my input value in React even with the onChange listener
- Why can't I change my input value in React even with the onChange listener
- Testing React Functional Component with Hooks using Jest
- How to implement Error Boundary with React Hooks Component
- How to focus something on next render with React Hooks
- How to mock history.push with the new React Router Hooks using Jest
- Deactivate input in react with a button click
- Lodash debounce with React Input
More Query from same tag
- ReactJS How can I push a data from SelectField to an object within an array?
- Uncaught TypeError: _firebase__WEBPACK_IMPORTED_MODULE_0__.app.auth is not a function
- Using material-ui with ecmascript6
- for what purpose we write e.target.name into the state definition statement?
- How to comment JSX code out in .js files in VSCode?
- need helping displaying table
- Using Spotify Web Playback SDK with React
- Why am I not able to route my app? react - react-router - redux-router
- left: auto property of css does not work in Internet Explorer
- Retrieving the type of JSX children
- No overload matches this call in saga call effect
- How to use popperComponent Props while using useAutoComplete in material ui reactJS
- Call function on default when checkboxes are rendered
- Take Image from API and store it in a object
- Only show single array of objects from Rest api in React
- TypeError: Cannot destructure property 'id' of 'this.props.Name' as it is undefined. In ReactJS
- Render object in React
- How to import client-side HTML into Gatsby/React?
- How to add information pop-up for TextInput in React Native?
- ReactJs SyntaxError with ternary operator
- Correct syntax for props in SVG in jsx
- React bootstrap table 2 programmatically select filter
- Not able to call another action inside a action in react-redux
- How to have a separated file in js that handles the API response in Reactjs
- What is the best way to change a playing video in React
- Enzyme shallow testing with Material-UI
- Define Isomorphic React routes in Web API
- How can i get the specific array using Lodash in react js
- Owl Carousel with React
- set id in value field of select option in react.js