Lukas
Lukas

Reputation: 10340

React: Child Components Without JSX

I want to create React components and add child components to it without the use of JSX. I tried the following:

class ChildComponent extends React.Component {
  render() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("p", {}, "hello world");
  }
}

class Component  extends React.Component {
  render() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("div", {}, ChildComponent);
  }
}

I also tried this

const childComponent = createReactClass({
  render: function() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("p", {}, "hello world");
  }
});

const component = createReactClass({
  render: function() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("div", {}, childComponent);
  }
});

And I get this error:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

Upvotes: 3

Views: 1967

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281646

All you need to do to create element is to pass the third parameter as the React element instead of a normal argument. Make use of React.createElement to create an element out of the react ChildComonent class

class ChildComponent extends React.Component {
  render() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("p", {}, "hello world");
  }
}

class Component extends React.Component {
  render() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("div", {}, React.createElement(ChildComponent));
  }
}

Working codesandbox

Upvotes: 4

Related Questions