Reputation: 695
How can I use "if" statement in Context.Consumer? I need to check if context.state.showLoginBox is true, then show the div below.
class LogInBox extends Component {
render() {
return(
<MyContext.Consumer>
{(context) => (// context.state.showLoginBox ? => show div below
<div className="logInBoxWrapper" id="logInBoxId">
<div className="logInBox">
<h3>Войти</h3>
<form method="">
<input name="email" placeholder="Электронная почта" required/>
<input name="password" type="password" placeholder="Пароль" required/>
<button type="submit">Войти</button>
</form>
</div>
</div>
)}
</MyContext.Consumer>
);
}
}
Upvotes: 1
Views: 1697
Reputation: 281764
You can use a if statement
in context callback if you use explicit return like
class LogInBox extends Component {
render() {
return(
<MyContext.Consumer>
{(context) => {
if(context.state.showLoginBox) {
return <div className="logInBoxWrapper" id="logInBoxId">
<div className="logInBox">
<h3>Войти</h3>
<form method="">
<input name="email" placeholder="Электронная почта" required/>
<input name="password" type="password" placeholder="Пароль" required/>
<button type="submit">Войти</button>
</form>
</div>
</div>
}
return null;
}}
</MyContext.Consumer>
);
}
}
otherwise with implicit return you can use ternary operators
class LogInBox extends Component {
render() {
return(
<MyContext.Consumer>
{(context) => context.state.showLoginBox ? <div className="logInBoxWrapper" id="logInBoxId">
<div className="logInBox">
<h3>Войти</h3>
<form method="">
<input name="email" placeholder="Электронная почта" required/>
<input name="password" type="password" placeholder="Пароль" required/>
<button type="submit">Войти</button>
</form>
</div>
</div>
)}
</MyContext.Consumer> : null
}
}
Upvotes: 1