패스트캠퍼스 메가바이트스쿨 Day 26 (6주차 월요일 - React Style, ref DOM, Form, Error)

ctaaag·2022년 5월 16일
0
post-thumbnail

Today Topic : React Style, ref DOM, Form, Error


🗝 Keywords

✅ Style

✅ ref로 dom 다루기

✅ form

✅ Error



1. style

<script type="text/babel">
      function Button({ color, className = "", style, ...rest }) {
        return (
          <button
            style={{
              fontSize: 30,
              backgroundColor: "pink",
              borderRadius: 8,
              ...style,
            }}
            className={`button ${className}`}
            {...rest}
          />
        );
      }
      const element = (
        <>
          <Button style={{ borderRadius: "50%" }}>Green</Button>
          <Button
            className="blue"
            style={{ borderRadius: "8px", fontSize: "20" }}
          >
            Blue
          </Button>
          <Button className="red">Red</Button>
          <Button className="gray">Gray</Button>
          <Button className="black">Black</Button>
        </>

🚀 Style

  • 리액트에서 style은 element의 인라인 방식으로 선언할 수 있다. sytle = {{ borderRadius }} 이 때는 {{}}를 꼭 두개 붙여줘야함
  • 그런데 보통은 비슷한 형태의 element는 위와 같이 함수를 만들어서 사용함.
  • 함수를 만들어서 element를 만들 때는 인자로 className, color, style등을 받을 수 있고, 특정 값을 초기에 넣어주지 않고 싶다면 이름을 명시하지 않고 ...rest로 분해해서 할당을 해주는 것이 가능함
  • 만약 위의 인자로 명시가 된 함수는 return에 있거나, element 인라인안에서 꼭 선언이 되어야만 적용이 가능함
  • style은 객체이기 때문에 카멜케이스:"",의 형태로 선언해야 읽을 수 있다.
  • style 우선순위는 위의 클래스네임으로 선언된 것 보다 color를 우선순위로 함. 즉, 위의 클래스네임을 통해 백그라운드 컬러가 선언이 되어있다고 해도 엘리먼트에서 컬러를 다시 설정하면 그것이 반영된다는 것.

2. ref로 dom 다루기

      const App = () => {
        React.useEffect(() => {     document.getElementById("input").focus();
        }, []);
        return (
          <>
            <input id="input" />
          </>
        );
      };
      ReactDOM.render(<App />,
      document.getElementById("root"));

🚀 getElement~로 dom을 다뤘을 때

  • useEffect로 따로 뺀 이유는 아직 앱함수 내에서 input이 만들어지지 않았기 때문에 App함수 실행 후에 사focus를 사용하기 위해서 진행함.
      const App = () => {
        const inputRef = React.useRef();
        const divRef = React.useRef();
        React.useEffect(() => {
          inputRef.current.focus();
          setTimeout(() => {
      divRef.current.style.backgroundColor = "pink";
          }, 1000);
        }, []);
        return (
          <>
            <input ref={inputRef} />
            <div
              ref={divRef}
              style={{ height: 100, width: 300, backgroundColor: "brown" }}
            />
          </>
        );
      };

🚀 ref로 DOM을 다뤘을 때

  • 함수 내에서 변수명 = React.useRef();로 선언을 하고
  • return 값으로 ref= {변수명}을 넣어주면 해당 엘리먼트를 선택할 수 있음.
  • 거기에 별도로 hook에서 해당 함수를 호출해줄 때는 변수.current.dom으로 선언하면 조작이 가능함.


3. form

      const rootElement = document.getElementById("root");
      const App = () => {
        const handleSubmit = (event) => {
          event.preventDefault();
          console.dir(event.target);
          alert(
            `FirstName: ${event.target.elements.fname.value}, LastName:${event.target.elements.lname.value}`
          );
        };
        return (
          <>
            <form onSubmit={handleSubmit}>
              <label htmlfor="fname">First name:</label>
              <br />
              <input type="text" id="fname" name="fname" defaultValue="John" />
              <br />
              <label htmlfor="lname">Last name:</label>
              <br />
              <input type="text" id="lname" name="lname" defaultValue="Doe" />
              <br />
              <br />
              <input type="submit" value="Submit" />
            </form>
          </>
        );
      };
      ReactDOM.render(<App />, document.getElementById("root"));

🚀 submit활용

  • value => defaultValue
  • for => htmlfor
  • console.dir은 해당 객체의 모든 내용을 콘솔에 찍어봄
  • 초기값을 무시하고 싶을 때는 preventDefault()를 사용할 것
  • onSubmit은 이벤트가 발생하면 onSubmit을 실행할 수 있도록 하는 것.

🚀 input 활용

  const App = () => {
        const [message, setMessage] = React.useState("");
        const [phoneNumber, setPhoneNumber] = React.useState("");
        const handleSubmit = (event) => {
          event.preventDefault();
          alert(phoneNumber);
        };
        const handleChange = (event) => {
          if (event.target.value.startsWith(0)) {
            setMessage("Phone Number is vaild");
            setPhoneNumber(event.target.value);
          } else if (event.target.value.length === 0) {
            setMessage("");
            setPhoneNumber("");
          } else {
            setPhoneNumber("");
            setMessage("Phone Number should starts with 0");
          }
        };
        return (
          <>
            <form onSubmit={handleSubmit}>
              <label htmlFor="phone">Phone Number:</label>
              <br />
              <input
                id="phone"
                name="phone"
                onChange={handleChange}
                value={phoneNumber}
              />
              <br />
              <p>{message} </p>
              <br />
              <button
                type="submit"
                disabled={
                  !phoneNumber.length === 0 ||
                  message !== "Phone Number is vaild"
                }

                Submit
              </button>
              <p>{phoneNumber}</p>
            </form>
          </>
        );
      };
      ReactDOM.render(<App />, document.getElementById("root"));
  • 특정 조건에서 input을 관리하고 싶을 때는 onChange를 통해 변화되는 값에 함수로 관리할 수 있다
  • value값 자체를 관리하게 되면 특정 조건에서 입력 자체를 막을 수도 있다.
  • button은 disabled를 통해서 관리할 수 있다.


4. Error

      class ErrorBoundary extends React.Component {
        state = { error: null };
        static getDerivedStateFromError(error) {
          return { error };
        }

        render() {
          const { error } = this.state;
          if (error) {
            return <this.props.fallback error={error} />;
          }

          return this.props.children;
        }
      }

      const Child = () => {
        throw new Error("Something Wrong.......");
        return <p>Child...</p>;
      };

      const Fallback = ({ error }) => {
        alert(error.message);
        return <p> THERE is some ERROR...</p>;
      };

      const App = () => {
        return (
          <>
            <p>App</p>
            <ErrorBoundary fallback={Fallback}>
              <Child />
            </ErrorBoundary>
          </>
        );
      };
      ReactDOM.render(<App />, document.getElementById("root"));

🚀 error

  • 에러가 났을 때 전체페이지가 안 뜨는 것이 아니라 특정 에러가 난 부분을 표시해주면서 에러 핸들링을 할 수 있는 방법
  • ErrorBoundary클래스 컴포넌트 이용해서 해당 클래스 안에서만 사용할 수 있는 getDerivedStateFromError 함수를 이용한다.
  • error가 났을 때 보여줄 element를 생성함 여기서는 fallback이라고 정의했음.
profile
프로그래밍으로 지속가능한 세상을 꿈꾸며

0개의 댓글