개발/🟦 React

🟦 [React] 텍스트 불러올 때 <br /> 사용하기 => <React.Fragment> 이용

비니_ 2025. 3. 20. 09:30
728x90

✅ 문제점: 내가 위 태그로 값을 불러오고 있었는데 <br/>까지 같이 텍스트로 불러와짐

✅ 구현하고 싶던 방향: <br/>이 태그로 들어가게

 

 

문제 코드👇

{Array.isArray(method.files) ? method.files.join("<br/>") : method.files}

 

 

- map()을 사용하고 리턴값안에 React.Fragment 태그(빈 태그) 사용

=> <></> 로도 사용 가능하지만 key값을 넣어주기 위해 (<> 는 react 16버전 이상부터 가능)  React.Fragment 사용

=> React.Fragment를 사용하려면 import React from "react";를 해줘야함

=> ❗내가 한 실수: import { useState, React } from "react"; 로 했기 때문에 import가 안되고 있었음

=> import React, { useState } from "react"; 같이 하려면 이렇게 해줘야 함

// 변경 전
<td>
    {data.method?.map((method, index) => (
        <div key={index}>
            <strong>[ {method.type} ]</strong><br/>
            {Array.isArray(method.files) ? method.files.join("<br/>") : method.files}
            <br/><br/>
        </div>
    ))}
</td>

// 변경 후
import React from "react";

<td>
    {data.method?.map((method, index) => (
        <div key={index}>
            <strong>[ {method.type} ]</strong><br/>
            {Array.isArray(method.files)
                ? method.files.map((file, index) => (
                    <React.Fragment key={index}>
                        {file} <br/>
                    </React.Fragment>
                ))
                : method.files
            }
            <br/><br/>
        </div>
    ))}
</td>
728x90