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
- Email and social sharing functionality
- Import a library only on the server side to use in getInitialProps
- slider images doen't get adjusted depending on the size of the screen
- ReactJS: How can I align form <Field>'s <input> and <button> and <h1> in a row inside a <div>?
- State of React child doesn't update after updating parent component
- I want pass book data to the view page to the edit page in react js
- Ant design button color update
- Disconnect Reflux listenTo method
- Infinite loop in React button
- React-Redux - How to set fields inside state of application?
- TypeORM relations and express
- Modals Using React
- How to have a parent/global Resource in React-Admin?
- Want to push element in to array of state variable
- react-chartjs-2 how to set multiple background levels within a line chart
- Render the form input binding from external function in react
- How should a component access data from a store?
- How to pass input value from the search bar to another component?
- Is there a good way to use private variables and methods in React.js
- React Unexpected Token with Async
- Updating Props (or State) in Inputs Mapped from Object Array with React
- (React) useDispatch TypeError: Object(...) is not a function handleChange
- Show README.md file contents
- Router Dispatch onEnter
- React Day Picker calendar overlay pops up behind other components
- How to change state value when input is checked with useState hook
- React Js require 'fs'
- How to load image file inline in MERN Stack Application
- React-JS : Initializing a global variable in componentDidMount but not getting its value in render
- How to use props with styled-components in switch statement