Dan Rubio Dan Rubio - 3 months ago 31
React JSX Question

Why won't my react variable render on the DOM?

I am learning react and am using this github repository from the official React website create-react

I have followed the instructions and began editing the

App.js
that is provided.

In my App.js file I am creating a
Todo
class and rendering it on the DOM with the
#container
id.

Here is the
App.js
file:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends 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>
);
}
}

var Todo = React.createClass({
render: function() {
return (
<h1 className="todo">Hello</h1>
);
}
});

export default App;


Here is the
index.js
file:

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

ReactDOM.render(
<App />,
document.getElementById('root')
);

ReactDOM.render(
<Todo />,
document.getElementbyId('container')
);


And here is the
index.html
file:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="./src/favicon.ico">
<title>React App</title>
</head>
<body>
<div id="root"></div>
<div id="container"></div>
</body>
</html>


When I open the web page I get this error
21:5 warning 'Todo' is defined but never used no-unused-vars


What is going on here?

Answer

You need to export the Todo variable (a React class) along with the App component. To do this use export followed by braces and the things you want to export:

export {
    Todo,
    App
};

This makes this public and importable. Both are now able to be use in a different file. Import like this:

import { App, Todo } from './App';

This will import both of the exported components and you will be able to access them both. Then render like you always do:

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

ReactDOM.render(
    <Todo />,
    document.getElementbyId('container')
);