react input state management

BackEnd_Ash.log·2020년 7월 7일
0

react

목록 보기
16/41

input state manage

input state manage of one

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>
     </>
	);
};

many input state manage

InputSample.js

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;

useRef use focus

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;
profile
꾸준함이란 ... ?

0개의 댓글