<React> Input Component로 다루기

·2023년 6월 22일
0

React

목록 보기
9/23

React를 좀 더 잘 다루기 위하여 따로 강의를 보며 개인 연습 프로젝트를 하며 학습하고 있는데, 오늘은 Input 컴포넌트를 따로 생성하여 props를 입맛대로 생성하여 사용하는 방법을 학습했다.

방법은 전개구문 을 활용하여 모든 props를 불러오는 것인데,
나중에 모를 때 표시 되어있는 부분을 다시 보면 금방 이해할 수 있을 것 같다.

Input Component를 사용하는 부모 Component

import React, { useState } from "react";
import Button from "../../UI/Button/Button";
import Input from "../../UI/Input/Input";
import styled from "./MealItemForm.module.css";

const MealItemForm = () => {
  return (
    <form className={styled.form}><Input
        label="Amount"
        input={
          	{
	          id: "amount",
    	      type: "number",
        	  min: "1",
	          max: "5",
	          step: "1",
	          defaultValue: "0",
        	}
		}
      />
      <button type="submit">+ Add</button>
    </form>
  );
};

export default MealItemForm;

Input Component

import React from "react";
import styled from "./Input.module.css";

const Input = (props) => {
  return (
    <div className={styled.input}>
      <label htmlFor={props.label} id={props.input.id}>
        {props.label}
      </label>
      {/* input 요소를 전개구문으로 모두 불러와서 적용 */}<input {...props.input} />
    </div>
  );
};

export default Input;

결과

느낀점

Input 컴포넌트를 따로 만들고, 전개구문을 활용하여 부모 컴포넌트에서 props를 내려주면, 입맛에 맞게 하나의 input 컴포넌트로 여러 곳에서 재사용이 가능할 것 같다는 생각이 들었다.

아주 좋은 방법을 학습한 것 같아 기분이 좋다. 😙

0개의 댓글