Kuan Kuan - 3 months ago 19
React JSX Question

React Only return props.children

All:

I am pretty new to React, I wonder how can I build a logic only component without adding any element(only used to processing some data), something like:

class LogicCom extends Component {
constructor(props){super(props);this.props = props;}
render(){
return (
{this.props.children}
)
}
}

Answer

What you have will work IFF there is only one child (and you fix your syntax errors). However, children can be an array of many children and you cannot return an array in a render function. So, you either must do one of two things...

1) Enforce that your component only accepts a single child with React.Children...

class LogicCom extends Component {
    render(){
        // this will throw if there are many children
        return React.Children.only(this.props.children)
    }
}

2) Wrap the children in another component...

class LogicCom extends Component {
    render(){
        return <div>{ this.props.children }</div>
    }
}
Comments