Luke
Luke

Reputation: 21236

React Redux render connected component

I'm using the connect function React Redux to connect my store to a React component. After it is connected I want to render the component. This works:

class Init extends React.Component {
  render() {
    return (
      <View /> // Is really more elaborate
    )
  }
}

Connect it to the store:

const InitPage = connect(
  state => ({
  }),
  dispatch => ({
  })
)(Init)

Now render it:

class App extends React.Component {
  render() {
    const content = <InitPage />

    return (
      {content}
    )
  }
}

Great. This all works. However...

When I place the connect inside a function and return the connect, as in:

const getInitPage = () => {
  const InitPage = connect(
    state => ({
    }),
    dispatch => ({
    })
  )(Init)

  return InitPage
}

If I now try to render the component:

class App extends React.Component {
  render() {
    const content = getInitPage()

    return (
      {content}
    )
  }
}

I get an error:

Invariant Violation: React.Children.only expected to receive a single React element child.

What is the correct way to return a Redux "connected" component from a function?

Upvotes: 0

Views: 523

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

In case you are returning the component from the function, you need to render it like

class App extends React.Component {
  render() {
    const Content = getInitPage()

    return (
      <Content/>
    )
  }
}

Also make sure the componentName starts with a uppercase character.

Upvotes: 1

Related Questions