A
A
Anya Kolomenskaya2020-10-15 08:14:49
JavaScript
Anya Kolomenskaya, 2020-10-15 08:14:49

How to conditionally pass a parameter to a component in React?

How to conditionally pass a parameter to a component in React? I thought that something like this could turn out, but this code crashes with an error:

<Page title="SOME TEXT" {this.state.content === null ? "no_text" : null}>

We need to make sure that if this.state.content is null , then it is passed If this.state.content is equal to anything else, then it is passed
<Page title="SOME TEXT" no_text>

<Page title="SOME TEXT">

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dasha Tsiklauri, 2020-10-15
@Anya_Koya

<Page title="SOME TEXT" no_text={this.state.content === null}>

UPD:
<Page title="SOME TEXT" {...(this.state.content === null?{no_text:true}:{})}>

I
iamsergo, 2020-10-15
@iamsergo

As I understand it, no_text is a boolean parameter (true or false).
You can do it like this: !!value - casts value to a boolean value:
<Page title='...' no_text={!!this.state.content}>

!!null === false
!!'' === false
!![] === true
!!'aaa' === true

Perhaps this is a typo or not the entire component, but it is written like this
<Page /> или <Page></Page>, а у вас <Page>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question