ParadoxicalEnigma ParadoxicalEnigma - 3 months ago 12
Javascript Question

this.props seems to be undefined and I can't figure out why

I'm very new to React js and I'm trying to do something very simple, when a user types into the text-input the text in the p tag on top of it should change as the user is typing. Here's the relevant code:

index.js

import { render } from 'react-dom'
import App from './components/App'

var Name = React.createClass({
getInitialState: function() {
return {name: ''}
},
changeName: function(event) {
this.setState({
name: event.target.value
});
},
render: function() {
return (
<div>
<p>Your name is: {this.state.name}</p>
<App setName={this.changeName} />
</div>
)
}
});

render( (<Name />), document.getElementById('content'));


App.js
import style from '../style/base.scss';

export default function() {
return (
<div>
<input type="text" placeholder="Enter text!" className="fancy" onChange={this.props.setName} />
</div>
);
}


I thought this would work, but instead nothing gets rendered to the page at all. When I check the console on the browser, it tells me: "Uncaught TypeError: Cannot read property 'props' of undefined". This must mean that the "this" object is undefined but I can't think of a reason why. I didn't use es6 class syntax so I thought that "this" would work fine. Can someone tell me what's going on? Thank you in advance for anyone willing to look at this.

Answer

You are using App.js as a stateless functional component. They don't have this. Instead the props are passed as an object parameter to your function. You could fix this by either accepting an object (such as props) in your function and accessing props.setName, or you could pull it out with destructuring and define your function like this: export default function({ setName }) { and then referencing setName instead of this.props.setName