0

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>
        );
    }
}
Ivan Burzakovskiy
  • 655
  • 1
  • 5
  • 20

1 Answers1

1

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
    }
}
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318