React(1) ≡ 기초

Acrylic·2024년 3월 13일

React 기초

import { createRoot } from "react-dom/client";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render();

React를 쓰려면 일단 이 root라는 것을 써야 한다.
저 코드가 가장 기초적이고 여기서 root.render 안에 html과 비슷한 작업을 진행하면 된다.
참고로 웹 컴파일러가 아니고 직접 create-react-app을 쓴다면 알아서 넣어 주기에 이런 게 있구나 하고 넘어가면 된다.

/*
root.render(
     <Header />
     <MainContent />
     <Footer />
 );
오류 */

root.render(
  <div className="index">
    <Header />
    <MainContent />
    <Footer />
  </div>
);

render는 태그를 여러 개 쓰려고 하면 오류가 발생한다. 다만, 이렇게 div로 묶고 그 안에 다른 요소들을 넣어 주면 오류가 발생하지 않는다.

<React.StrictMode>
  <App />
</React.StrictMode>

index.jscreate-react-app을 쓰면 이런 게 render 안에 들어가 있다.
App.js가 있을 텐데 그걸 연결하는 것이다.

import { App } from "./App";

참고로 React.js 표시를 안 해 줘도 알아서 .js로 인식하고 import 해 준다.
(.jsp로 했으면 .jsp로 인식한다)

App.js에 들어가면 함수나 클래스가 있을 건데 거기서 작업해 주면 된다.

import, export

export를 했으면 import를 하는 게 인지상정이다.
export function App() 이렇게 해도 되지만, create-react-appfunction을 두고
다음에 export default App;을 사용한다.

function App() {
  return (
    <div>
    </div>
  );
}

export default App;

이렇게 하면 React 기초에서 설명했던 import가 작동할 수 있게 된다.

Component 관리

import, export 할 줄 알면 이제 component 관리도 쉬울 것이다.

// App.js

import { Footer } from "./components/Footer.js";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

// components/Footer.js

import { createRoot } from "react-dom/client";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(<Footer />);

export function Footer() {
  return (
    <div className="Footer">
      <p>Copyright © 2023 deterism.co.,Ltd. All rights reserved.</p>
    </div>
  );
}

이렇게 파일을 따로 둘 수 있다. 여기는 export function을 쓰는 방식으로 코드를 짜 보았다.
추가로, 사진은 html 태그처럼 써도 되나 주의할 점은 src = "/"을 쳤다면 초기 경로가 public이란 점이다.
아이콘을 쓰고 싶다면 react 내에 있는 걸 쓰면 되는데 npm install ~ 등 할 게 좀 있어 다음 편에 설명한다.
이 정도만 배워도 html과 별반 다를 것 없이 거의 똑같이 쓸 수 있는데 관리가 좀 더 수월해진 html을 쓸 수 있다고 보면 된다.

profile
프런트엔드 개발자 지망생

0개의 댓글