Reputation: 171
I'm currently learning React, I have a simple component that renders simple plain text. I created a small component where on getting simple plain text from props, but I was surprised. when I assign a simple static value on variable then it's working fine but when I try to get that value from the props, it does not work.
here is sample snippet code.
let TextEditor = React.createClass({
getInitialState: function () {
var content = "test 2";
var content = this.props.plainText
return {
content: content
};
},
render() {
return (
<div>
<Editor
value={this.state.content}
/>
</div>
)
}
})
Advance Thanks for your clue
Upvotes: 0
Views: 60
Reputation: 77
You can use the following code to achieve the expected result :
class MyComp extends React.Component {
constructor(props) {
super(props);
this.state = { content: this.props.plainText };
}
render() {
const { content } = this.state;
return (
<div>
<Editor value={content} />
</div>
);
}
}
Upvotes: 0
Reputation: 162
getInitialState seems a little dated now. I'd recommend at least looking into the ES6 way of doing things. It's also better not to set props to state immediately in your constructor, you could update the state when the component has mounted instead. There are other ways of getting your props into your component so it's working taking a look at the react docs in a bit more detail.
As a basic ES6 example....
class MyComp extends React.Component {
constructor(props) {
super(props);
this.state = { content: '' };
}
componentDidMount = () => {
const { plainText } = this.props;
this.setState({ content: plainText });
}
render() {
const { content } = this.state;
return (
<div>
<Editor value={content} />
</div>
);
}
}
Upvotes: 1