inputSample.js
import React from "react";
const InputSample=()=>{
return (
<>
<h1>TEXT</h1>
<input type="text" placeholder="입력하세요"/>
<button>Reset</button>
</>
);
};
export default InputSample;
it manages the value input to input as inputText state and initializes inputText when the reset button is pressed.
import React , {useState} from "react";
const InputSample = () =>{
const [inputText , setInputText] = useState("");
const onChangeInput = e => {
setInputText(e.target.value);
};
const onReset = () =>{
setInputText("");
};
return (
<>
<h1> {inputText} </h1>
<input
type="text"
value={inputText}
placeholder="input...."
onChange={onChangeInput}
/>
<button onClick={onReset}>Reset</button>
</>
);
};
import React , {useState} from "react";
const InputSample = () => {
const [user , setUser] = useState({
username : "",
age : ""
});
const {username , age} = user;
const onChangeInput = e => {
const {name , value} = e.target;
setUser({ ...user , [name] : value});
};
const onReset = () => {
setUser({ username : "" , age : "" });
};
return (
<>
<h1>
name : {username} , age : {age}
</h1>
<input
type = "text"
name = "username"
value = {username}
placeholder = "input name.."
onChange = {onChangeInput}
/>
<input
type = "number"
name = "age"
value = {age}
placeholder = "age"
onChange = {onChangeInput}
/>
<button onClick={onReset}>Reset</button>
</>
);
};
export default InputSample;
you can do focus using useRef
it is can access certain DOM
Using this feature, you can focus on a specific name input when the reset button is pressed.
import React , {useState , useRef } from "reaact";
const InputSample = () => {
const inputRef = useRef(); // ref object create
const [user , setUser] = useState({
username : "",
age:""
});
const { username , age } = user;
const onChangeInput = e => {
const { name , value } = e.target;
setUser({ ...user , [name] : value });
};
const onReset = () =>{
setUser({ username : "" , age : "" });
inputRef.current.focus();
};
return (
<>
<h1>
name : {username} , age : {age}
</h1>
<input
type = "text"
name = "username"
value = {username}
placeholder = "name"
onChange = {onChangeInput}
ref = {inputRef} // ref value setting at dom for accees
<input
type = "number"
name = "age"
value = {age}
placeholder = "age"
onChange = {onChangeInput}
/>
<button onClick = {onReset}>Reset</button>
</>
);
};
export default InputSample;