React

다시 시작하는 리액트 - 리액트 심화 2 Quiz

min' 2023. 5. 2. 00:05
728x90
반응형

 

- Quiz : 텍스트 입력기를 만들어보자!

우측 인풋에 텍스트를 입력하고 [완성] 버튼을 누르면 좌측 네모 박스에 입력한 텍스트가 나오게 해보기

 

- Quiz 설명 : 그간 배운 내용을 바탕으로 텍스트 입력기를 만들어보자!

힌트:
1. 좌측 네모 박스, 우측 인풋, [완성]버튼를 각기 다른 컴포넌트로 분리해서 만들어봅시다.
2. 텍스트 값을 가져올 땐 useRef()를 사용하세요.
3. useState()를 사용해서 네모 박스에 값을 넣어주세요.
4. useState()는 App 컴포넌트에서 만들어주세요.

 

 

- 내가 만든 것.

 

component를 각자 따로 만들어주라고 했기 때문에

SquareBox, TextInput, SuccessBtn component를 생성해줌.

 

- App.js

import { useRef, useState } from "react";
import SquareBox from "./components/SquareBox";
import TextInput from "./components/TextInput";
import SuccessBtn from "./components/SuccessBtn";
import styled from "styled-components";

const Wrap = styled.div`
  width: 100%;
  height: 100vh;
  padding: 40px;
  box-sizing: border-box;

  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
`;

const InputWrap = styled.div`
  width: 30%;
  height: 100%;
  padding: 60px;
  box-sizing: border-box;
`;

function App() {
  const [text, setText] = useState("");
 
  const inputTextRef = useRef(null);

  return (
    <Wrap>
      <SquareBox text={text} />
     
      <InputWrap>
        <TextInput inputTextRef={inputTextRef} />
        <SuccessBtn inputTextRef={inputTextRef} setText={setText} />
      </InputWrap>
    </Wrap>
  );
}

export default App;
- SquareBox.js

import React from "react";
import styled from "styled-components";

const BoxWrap = styled.div`
  width: 70%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  padding: 60px;
  box-sizing: border-box;
  border-radius: 10px;
`;

export default function SquareBox({ text }) {
  return (
    <BoxWrap>
      <h1 style={{ margin: 0, color: "white" }}>{text}</h1>
    </BoxWrap>
  );
}
- TextInput.js

import React from "react";
import styled from "styled-components";

const Input = styled.input`
  width: 100%;
  height: 60px;
  padding: 10px;
  box-sizing: border-box;

  font-size: 1rem;

  &::placeholder {
    color: #ccc;
  }
`;

export default function TextInput({ inputTextRef }) {
  return <Input ref={inputTextRef} placeholder="Write text..." />;
}

- SuccessBtn.js

import React from "react";
import styled from "styled-components";

const Btn = styled.button`
  width: 100%;
  height: 60px;
  background-color: rgba(0, 0, 0, 0.8);

  margin-top: 20px;
  padding: 10px;
  box-sizing: border-box;

  color: white;
  font-size: 1rem;

  transition: all 0.5s;

  outline: none;

  &:hover {
    background-color: white;
    border: 3px solid #666;

    color: black;

    outline: none;
  }
`;

export default function SuccessBtn({ setText, inputTextRef }) {
  return (
    <Btn
      onClick={() => {
        setText(inputTextRef.current.value);
        inputTextRef.current.value = "";
      }}
    >
      Success
    </Btn>
  );
}

 

 

만든 화면 찰-칵-!

 

728x90
반응형