React 조건부 렌더링2 논리 연산자
※ 조건부 렌더링 : 조건에 따라 다양한 컴포트 보여주기
조건부 렌더링1 : https://tadaiswhatever.tistory.com/21
1. 논리 연산자 사용 방법
- { 조건 && 엘리먼트}
function Sample(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
// {조건 && 엘리먼트}
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
<Sample unreadMessages={messages} />
, document.getElementById('root')
);
2. 삼항 연산자 사용 방법
- { 조건 ? 'true일 경우' : 'false일 경우' }
function Sample(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0
? 'true입니다.'
: 'false입니다.'
}
</div>
);
}
- '(따옴표)를 없애고 컴포넌트를 작성할 수도 있습니다.
function LoginInButton(props) {
return (
<button>
LogIn
</button>
);
}
function LogOutButton(props) {
return (
<button>
LogOut
</button>
);
}
function Sample(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
// 삼항 연산자 조건에 따른 컴포넌트 보여주기
{unreadMessages.length > 0
? <LoginInButton />
: <LogOutButton />
}
</div>
);
}
** 조건에 따라 null을 반환하여 컴포넌트 숨기기.
(일반 javascript처럼 return;으로만 끝내면 오류가 발생합니다. 반드시 return null;을 해주셔야 합니다.)
function WarningBanner(props) {
if (!props.warn) {
return null;
}
return (
<div className="warning">
Warning!
</div>
);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true};
this.handleToggleClick = this.handleToggleClick.bind(this);
}
handleToggleClick() {
this.setState(state => ({
showWarning: !state.showWarning
}));
}
render() {
return (
<div>
<WarningBanner warn={this.state.showWarning} />
<button onClick={this.handleToggleClick}>
{this.state.showWarning ? 'Hide' : 'Show'}
</button>
</div>
);
}
}
ReactDOM.render(
<Page />,
document.getElementById('root')
);
이전 글 : 2021.11.09 - [UI/React] - React 조건부 렌더링1 if
React 조건부 렌더링1 if
※ 조건부 렌더링 : 조건에 따라 다양한 컴포트 보여주기 - JavaScript와 같이 보여주기가 가능합니다. 1. if문 사용 방법 - 아래 두 개의 컴포넌트가 존재합니다. function UserGreeting(props) { return Welcome..
tadaiswhatever.tistory.com
다음 글 : 2021.11.17 - [UI/React] - React list와 key / React key
React list와 key / React key
※ List (map함수를 이용하여 list 엘리먼트를 반환받음) - javascript map // 배열 선언 const numbers = [1, 2, 3, 4, 5]; // .map 함수를 이용하여 list 엘리먼트를 반환받음. const listItems = numbers.map(n..
tadaiswhatever.tistory.com