L Becker
L Becker

Reputation: 755

Conditionally Render Child Component within Parent Component

I have a parent component DataTable that has Column child components. I want to include a specific Column child component if a prop is set to true. I've tried logical && and the ternary operator. The problem is that I can't pass any null or undefined value to DataTable. Logical && and the ternary operator seem to be providing a false, null, or undefined value as a child to DataTable when this.props.hasMiddleName is false. How can I fix this code so I do not pass any falsy values when this.props.hasMiddleName is false?

<DataTable dataUrl={this.props.url}>
    <Column Header={"First Name"} />
    { this.props.hasMiddleName &&
       <Column Header={"Middle Name"} />
    }
    <Column Header={"Last Name"} />
</DataTable>

Upvotes: 2

Views: 517

Answers (1)

Vencovsky
Vencovsky

Reputation: 31605

You should create an array of children in another function.

renderChildren = () => {
    let children = [<Column Header={"First Name"} />]
    if(this.props.hasMiddleName) {
        children.push(<Column Header={"Middle Name"} />)
    }
    children.push(<Column Header={"Last Name"} />)
    return children
}

And inside DataTable you call the function wich will render it's children.

<DataTable dataUrl={this.props.url}>
    {this.renderChildren()}
</DataTable>

Upvotes: 2

Related Questions