4. 동적 값 출력 및 활용

cheonbi·2024년 12월 10일
0

React

목록 보기
6/11

아래와 같은 페이지가 있다고 하자

React Essentials 옆에 있는 내용을 동적으로 바꾸고 싶다면 어떻게 해야할까?

function Header(){
    return  (
        <header className="App-header">
            <h1 className="App-header__title">React Essentials</h1>
            <p>Fundamental React concepts you will need for almost any app you are going to build</p>
        </header>
    );
}

위와 같은 컴포넌트로 내보내고 있다.
Fundamental 부분을 동적으로 바꿀려면

const reactDescriptions = ['Fundamental', 'Crucial', 'Core'];

function genRandomInt(max) {
    return Math.floor(Math.random() * (max + 1));
}

JSX, React에서는 중괄호를 활용한다.
JSX와 리액트에게 동적인 값을 출력하고 싶다고 명령

이 중괄호 사이에 원하는 자바스크립트 표현을 자유롭게 추가
중괄호 사이에 넣은 자바스크립트 표현 코드가 실행

❗ Important ❗
if-statements , for-loops , function definitions and other block statements are not allowed here! Only expressions that directly produce a value

function Header(){
    return  (
        <header className="App-header">
            <h1 className="App-header__title">React Essentials</h1>
            <p>{reactDescriptions[genRandomInt(2)]} React concepts you will need for almost any app you are going to build</p>
        </header>
    );
}

reactDescriptions 는 상수로 정의 되었고 배열이다.
index로 접근이 가능하고
genRandomIntreturn 값을 index로 활용해
reactDescription 의 값 중 하나를 가져온다.

More
중괄호에 정의되는 내용을 따로 빼서 관리하면 더 좋지 않을까?

보통 JSX 코드를 단정하게 유지하는 것을 선호하여 표현 결과는 다른 곳에 저장하고
상수에 불러들이는 용도로 사용한 것이 좋을 수 있다

function Header(){
    const description = reactDescriptions[genRandomInt(2)];
  
    return  (
        <header className="App-header">
            <h1 className="App-header__title">React Essentials</h1>
            <p>{description} React concepts you will need for almost any app you are going to build</p>
        </header>
    );
}
profile
༼ つ ◕_◕ ༽つ

0개의 댓글