Reputation: 195
I'm new to building apps using React. After downloading the 'Getting Started' app directly from the repo I started the server and the default app rendered properly. I tried to add a Menu component by following the tutorial here, but the app fails to render after compiling with no errors. For more context, this app is saved in a file called App.js, not a file with .jsx extension.
I think the issue is with the insertion of JS code via {} into the HTML within MenuExample.render()
. If I replace the body of MenuExample.render()
with the simple HTML code commented out in the function, the app renders. Can someone please shed some light as to why the app isn't rendering? Thanks for all the help.
Please see the full code below.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
/* eslint no-var:0*/
/* eslint func-names:0*/
/* eslint prefer-arrow-callback:0*/
/* eslint class-methods-use-this:0*/
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>
<MenuExample items={ ['Home', 'Services', 'About', 'Contact Us'] }/>
</div>
);
}
}
class MenuExample extends Component {
// eslint-disable-next-line
getInitialState() {
return { focused: 0 };
}
clicked(index) {
this.setState({ focused: index });
}
// eslint-disable-next-line
render() {
var self = this;
return (
<div>
<ul>{this.props.items.map(function (m, index) {
var style = '';
if (self.state.focused === index) {
style = 'focused';
}
return <li className={style} onClick={self.clicked.bind(self, index)}>{m}</li>;
}) }
</ul>
<p> Selected: {this.props.items[this.state.focused]} </p>
</div>
// Simple HTML that works
// <p> Foo </p>
);
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
Upvotes: 2
Views: 394
Reputation: 1039
You're trying to use the getInitialState
lifecycle method inside your react component created using es6
classes, which isn't supported. You should change to a constructor and setting your initial state inside of it.
class MenuExample extends Component {
// eslint-disable-next-line
constructor(props) {
super(props);
this.state = { focused: 0 };
}
...
It is explained here.
Upvotes: 4