2

I'm pretty confused with the react-native syntax. I was trying to dynamically render a wrapper (CardSection) if numberChildrenLabel is > 0. Then depending on the number children I want to render x number of components. What I'm doing currently doesn't work and I think it's a pretty messy (even if I do fix the syntax errors). What is the best way of rendering multiple components based on an input?

render(){
    return(
          ...
          {
          this.state.numberChildrenLabel > 0 ?
          <CardSection>
            <Text style={{ flex: 2}}>Children age:</Text>
            <View style={{ flex: 3}}>
              {
                for(var i=0; i<this.state.numberChildrenLabel; i++){
                  return(
                    <Text>child{i}</Text>
                  );
                }
              }
            </View>
          </CardSection>
          :
          <View/>
          }
          ...
    );
}

1 Answer 1

4

Inside brackets, you need an expression. What's inside for loop is a statement. Also, return outputs something from within a function; you cannot use it in this way.

I haven't tested the below code, but it should work.

render(){
        return(
              ...
              {
              this.state.numberChildrenLabel > 0 ?
              <CardSection>
                <Text style={{ flex: 2}}>Children age:</Text>
                <View style={{ flex: 3}}>
                  {
                    Array(this.state.numberChildrenLabel).fill().map((_, i) => i).map(i => <Text>child{i}</Text>)
                  }
                </View>
              </CardSection>
              :
              <View/>
              }
              ...
        );
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.