Tomek Buszewski
Tomek Buszewski

Reputation: 7935

React and importing classes

I am trying to build a view with partials. For this, I created two classes - SmallPost and PostsList.

SmallPost is a small class that renders JSON, like so:

import React from 'react';
import { render } from 'react-dom';

export default class SmallPost extends React.Component {
  constructor(props) {
    super(props);

    this.post = this.props.data;
  }

  render() {
    /* ... */
  }
}

And PostsList utilizes it:

import React from 'react';
import { render } from 'react-dom';
import { SmallPost } from './SmallPost';

class PostsList extends React.Component {
  constructor(props) {
    super(props);

    this.list = '/wp-json/wp/v2/posts';
    this.posts = null;
    this.state = {
      posts: null,
      loaded: false
    }
  }

  componentDidMount() {
    const request = new XMLHttpRequest();

    request.open('GET', encodeURI(this.list));
    request.onload = () => {
      this.setState({
        posts: JSON.parse(request.responseText)
      }, this.parsePosts);
    };
    request.send();
  }

  parsePosts() {
    this.posts = this.state.posts.map(post => {
      this.setState({ loaded: true });

      return (
        <SmallPost data={post} />
      )
    });
  }

  render() {
    if(!this.state.loaded) {
      return (<div>Loading...</div>);
    } else {
      return (<div className="posts--loaded">{this.posts}</div>);
    }
  }
}

render(<PostsList />, document.getElementById('posts'));

Nothing fancy, as you see. But it doesn't work - I get

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).

from console. When I put the SmallPost code inside PostsList file, it works. What can I do?

Upvotes: 4

Views: 12474

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47172

You're using the default export so you can't use the named import.

So you can change from

import { SmallPost } from './smallpost';

to

import SmallPost from './smallpost';

And if you're using Babel 6.x you might need to do

import SmallPost from './smallpost';
let SmallPostComponent = SmallPost.default;

Upvotes: 6

Related Questions