Dan Rubio Dan Rubio - 2 months ago 7
Javascript Question

Can someone help pinpoint why I can't render state with React, ES6 in my component?

I am learning react and I've chosen to create a sample resume app using ES6. I'm trying to follow along as best as I can combining different blogs and tutorials for rendering state in my components but I'm having a little bit of trouble getting the hang of it.

For starters, here is a sample of my code in

App.js


class ContentBlock extends React.Component {
constructor(props) {
super(props);
this.state = { heading: '', body: '' };
}
setText() {
this.setState({ heading: "I'm Daniel", body: "I am about to be twenty seven years old" });
}
componentDidMount() {
{this.setText.bind(this)}
}
render() {
return (
<Media>
<Media.Left>
<Image src={this.props.src}/>
</Media.Left >
<Media.Heading>{this.state.heading}</Media.Heading>
<Media.Body>
<p>{this.state.body}</p>
</Media.Body>
</Media>
);
}
}


I'm using a combination of these three tutorials.

Official React ES6 tutorial

BabelJs tutorial for React ES6

Kirupa Tutorial on React

Aside from a warning on my ESLint, I'm experiencing no errors but the text is not rendering. What can I be doing wrong. If someone can just point me in the right direction that would be great. I've spent too much time trying to hack among all three how to do it correctly and a boost would be appreciated. Thanks.

#####Update

The
this.props.src
comes from a component that uses
ContentBlock
as sub component

class About extends Component {
render() {
return (
<div>
<ContentBlock src={danrubio} />
</div>
);
}
}


I specify the image and pass it onto the
About
component which
ContentBlock
will inherit.

Answer

All this statement: this.setText.bind(this) does, is just binds setText function to the context, but doesn't invokes it. Even more, you are binding it to the same context that it already has. No need in binding here.

Just change this:

componentDidMount() {
  {this.setText.bind(this)}
}

To:

componentDidMount() {
  this.setText()
}
Comments