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} ) } }
You can return children only without wrapping the children. Trick is to create a wrapper component then modify children into an array, which is required by React. Now you can simply just wrap anything else in this wrapper component. Now the elements inside the wrapper will render without having to wrap it in a DIV.
children} inside a <div> , the passed elements appear in the final output. React elements like <Contacts /> and <Chat /> are just objects, so you can pass them as props like any other data.
By invoking them between the opening and closing tags of a JSX element, you can use React children for entering data into a component. The React children prop is an important concept for creating reusable components because it allows components to be constructed together.
In React's JSX, a component with children is always identified by an opening tag and a closing tag. Each child must be placed between these two tags, just as we have seen above.
EDIT In React v16+, you can return strings and arrays from components. So, it is perfectly valid for a component to simply return its children...
render() { return this.props.children }
Read more about it in the docs.
ORIGINAL 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 must do one of two things...
class LogicCom extends Component { render(){ // this will throw if there are many children return React.Children.only(this.props.children) } }
class LogicCom extends Component { render(){ return <div>{ this.props.children }</div> } }
React components MUST have a single root DOM element to render.
From the official docs:
The render() method is required.
When called, it should examine this.props and this.state and return a single child element. This child element can be either a virtual representation of a native DOM component (such as or React.DOM.div()) or another composite component that you've defined yourself.
You can also return null or false to indicate that you don't want anything rendered. Behind the scenes, React renders a tag to work with our current diffing algorithm. When returning null or false, ReactDOM.findDOMNode(this) will return null.
In your case it's easy enough -- just wrap your this.props.children
in an outer element of some kind.
render(){ return ( <div>{this.props.children}</div> ) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With