[React] 공통 컴포넌트 세팅

zzincode·2022년 12월 27일

React

목록 보기
2/20
post-thumbnail

# button에 type지정

App.js

import "./App.css";

import MyButton from "./components/MyButton";

function App() {
  return (
    <div className="App">
      <MyButton
        text={"버튼"}
        onClick={() => alert("버튼클릭")}
        type={"positive"}
      />
      <MyButton
        text={"버튼"}
        onClick={() => alert("버튼클릭")}
        type={"negative"}
      />
      <MyButton text={"버튼"} onClick={() => alert("버튼클릭")} type={""} />
    </div>
  );
}

export default App;

MyBotton.js

const MyButton = ({ text, type, onClick }) => {
  return (
    <button
      className={["MyButton", `MyButton_${type}`].join(" ")}
      onClick={onClick}
    >
      {text}
    </button>
  );
};

MyButton.defaultProps = {
  type: "default",
}; //type을 전달하지 않으면 default

export default MyButton;

※ type이 default, positive, negative 외 다른 버튼이 들어오는 것을 막을려면?

const btnType = ["positive", "negative"].includes(type) ? type : "default";

→ type에 positive와 negative가 없는 글자가 오면 default로 설정

const MyButton = ({ text, type, onClick }) => {
  const btnType = ["positive", "negative"].includes(type) ? type : "default";
  return (
    <button
      className={["MyButton", `MyButton_${btnType}`].join(" ")}
      onClick={onClick}
    >
      {text}
    </button>
  );
};

MyButton.defaultProps = {
  type: "default",
};
//type을 전달하지 않으면 default

export default MyButton;

1개의 댓글

comment-user-thumbnail
2023년 1월 10일

글이 유익하네요! 잘 보고 가요!

답글 달기