Daniel Daniel - 17 days ago 12
Javascript Question

How do I correct this Uncaught RererenceError in Reactj?

I started getting this error when I added the channels array as a way to mock a list of channels in the beginning phases of my application.

index.js:7852 Uncaught ReferenceError: channels is not defined(…)

Here is the App.js file:

import React from 'react';
import ReactDOM from 'react-dom';

let channels = [
{name: 'Hardware Support'},
{name: 'Software Support'}
];

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

export default Channel


Here is the main.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import Channel from './App';

class ChannelList extends React.Component {
render(){
return (
<ul>
{this.props.channels.map(channel => {
return (
<Channel name={channel.name} />
)
}
)}
</ul>
)
}
}

class ChannelForm extends React.Component{
onChange(e){
console.log(e.target.value);
}
onSubmit(e){

}
render(){
return (
<form onSubmit={this.onSubmit.bind(this)}>
<input type='text' onChange={this.onChange.bind(this)} />
</form>
)
}
}

class ChannelSection extends React.Component {
render(){
return(
<div>
<ChannelList channels={channels}/>
<ChannelForm />
</div>
);
}
}

ReactDOM.render(<ChannelSection />, document.getElementById('app'));

Answer

As mentioned by @FelixKling, the channels variable isn't available to your main.js file, as it's not being exported from App.js. The simplest way to share this across both files would be to export is as a non-default export, then pull it in as part of your Channels import in Main.js

Like so:

// App.js
let channels = [
    {name: 'Hardware Support'},
    {name: 'Software Support'}
];

...

export channels; // this is the variable export
export default Channel; // this is the class export, which will be the default if no specific export is declared in your import

// Main.js
import Channel, { channels } from './App';
// `Channel` class is imported as usual, along with non-default `channels` export

You should also use const instead of let in your channels declaration, as you're not reassigning it.

const channels = ...