Ryan Ryan - 4 months ago 45
Javascript Question

Cannot find module whenever I add another component to React JS

I am working through a Udemy Tutorial on React, and something here does not make sense. Whenever I try to add a new component to a .js file, I get an error stating that the component file cannot be found. Here is what I mean:
Originally, I had these 2 files:

my main.js :



console.log('Hello World!');
import React from 'react';
import ReactDOM from 'react-dom';
import Channel from './Channel';

document.addEventListener('DOMContentLoaded', function() {
ReactDOM.render(
React.createElement(Channel, Object.assign({}, this.props, {name:'Ryan'})),
document.getElementById('My-Channel')
);
});




and my Channel



import React from 'react';


class Channel extends React.Component {
onClick(){
console.log('I was clicked');
}
render(){
return(
<li onClick={this.onClick.bind(this)}>{this.props.name}</li>
)
}
}

export default Channel;





This code actually works, and displays the proper 1 item list.

However, when I try to add another component to my Channel.js file, it breaks. No matter what I put in, it seems that adding another component does not work.
Ex :



import React from 'react';


class Channel extends React.Component {
onClick(){
console.log('I was clicked');
}
render(){
return(
<li onClick={this.onClick.bind(this)}>{this.props.name}</li>
)
}
}
class ChannelList extends React.Component{
render(){
return (
<ul>
<Channel name='Hardware Support'>
</ul>
)
}
}
export default Channel;





Do I have to create a new file every time I want to create a component? I can't imagine that being the case, so what would you suggest I do?
Here is the Exact Error I am getting

Even if I add a simple dictionary to the end of the file, I get the same error. Its as if the only thing in this Channel.js file can be the channel component

Thank you in advance for your help!

Answer

Not being able to find a module is almost always a sign of a syntax error (assuming the files are in the right location). In your case, it's never hitting export because the following is a syntax error:

class ChannelList extends React.Component{
    render(){
        return (
            <ul>
                <Channel name='Hardware Support'>
            </ul>
        )
    }
}

You're missing the closing tag!

Change <Channel name='Hardware Support'> to <Channel name='Hardware Support' />

Also it looks as though you should be doing:

export default ChannelList

and in your main file:

import ChannelList from './Channel'

ReactDOM.render(
  <ChannelList />,
  document.getElementById('My-Channel')
),