Bryan White Bryan White - 1 month ago 6
React JSX Question

What is wrong with my render method here?

I'm writing an example app over here to get my head around React but one of my simpler components is throwing an error that I can't seem to track.


Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file
it's defined in. Check the render method of
ContactListItem
.


Here's the code for the ContactListItem component.

import React, { Component } from 'react';
import { ListGroupItem } from 'react-bootstrap';
import { Link } from 'react-router';

class ContactListItem extends Component {
render() {
const { contact } = this.props;
return (
<ListGroupItem>
<Link to={'/contact/${contact.id'}>
<h4>{contact.name}</h4>
</Link>
</ListGroupItem>
);
}
}

export default ContactListItem;


It's a pretty simple class. Nothing sticks out to me as problematic. For completion's sake, here's the parent component.

import React, { Component } from 'react';
import { ListGroup } from 'react-bootstrap';
import ContactActions from '../actions/ContactActions';
import ContactStore from '../stores/ContactStore';
import ContactListItem from './ContactListItem';

function getContactListItem(contact) {
return (
<ContactListItem key={contact.id} contact={contact} />
);
}

class ContactsComponent extends Component {
constructor() {
super();
this.state = {
contacts: []
}
this.onChange = this.onChange.bind(this);
}

componentWillMount() {
ContactStore.addChangeListener(this.onChange);
}

componentDidMount() {
ContactActions.receiveContacts()
}

componentWillUnmount() {
ContactStore.removeChangeListener(this.onChange);
}

onChange() {
this.setState({
contacts: ContactStore.getContacts()
});
}

render() {
let contactListItems;

if ( this.state.contacts ) {
contactListItems = this.state.contacts.map(contact => getContactListItem(contact));
}
return (
<div>
<ListGroup>
{contactListItems}
</ListGroup>
</div>
);
}
}

export default ContactsComponent;

Answer Source

You get the error in ContactListItem#render() because Link is undefined. As of React Router v4, <Link /> is no longer a part of the react-router, but a part of the react-router-dom package. Changing this should fix your problem:

import { Link } from 'react-router-dom';