Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.Children.only expected to receive a single React element child error

I'm getting 'React.Children.only expected to receive a single React element child.' from the following code.

I have created a new react app using create-react-app and installed redux and react-redux, and created a simple reducer and creating store with that.

import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";

import logo from './logo.svg';
import './App.css';

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}


function productReducer(state = [], action) {
  return state;
}

const store = createStore(
  productReducer
);

ReactDOM.render((<Provider store={store}><App /> </Provider>), document.getElementById('root'));
like image 218
Elangovan Avatar asked Jul 05 '17 23:07

Elangovan


2 Answers

You have a space here:

                               ↓
<Provider store={store}><App /> </Provider>

JSX is kinda picky about spacing on single lines. The above essentially gets interpreted as:

<Provider store={store}><App />{' '}</Provider>

(In fact, Prettier will produce pretty much this exact output)

You can either remove the space:

<Provider store={store}><App /></Provider>

Or break it up on to multiple lines:

<Provider store={store}>
    <App />
</Provider>
like image 139
rossipedia Avatar answered Nov 16 '22 14:11

rossipedia


I had a similar problem and it turns out I had converted my App root from a function to a class, which means I had to change the syntax from this:

ReactDOM.render(
  <Provider store={store}>
    { App }
  </Provider>,
  document.getElementById('root')
);

To this:

ReactDOM.render(
  <Provider store={store}>
    { <App /> }
  </Provider>,
  document.getElementById('root')
);
like image 41
Niek Avatar answered Nov 16 '22 16:11

Niek