React | Setting props in a state doesn't work but only works if it is directly set in the render/return

React | Setting props in a state doesn't work but only works if it is directly set in the render/return
0

#1

My file structure is:

index.js
+--components
      +--App.js
      +--Editor.js
      +--Preview.js

App.js (snippet)

  render() {
    return(
      <div id="wrapper">
        <Editor changeHandler={this.changeHandler} markdown={this.state.markdown}/>
        <Preview markdown={this.state.markdown}/>
        <p>{this.state.markdown}</p>
      </div>
    );
  }

My question is all about the Preview.js.
When the this.props.markdown set in a state (i.e. text: this.props.markdown) and call at return (i.e. <p>{this.state.text}</p>. It will not work. But …

Preview.js (snippet)

class Preview extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: this.props.markdown,               <-------------HERE
      converter: new showdown.Converter()
    }
    this.createMarkup = this.createMarkup.bind(this);
  }

  createMarkup() {
    return {__html: this.state.converter.makeHtml()}
  }

  render() {
    this.state.converter.setOption('tables', 'true');
    return (
      <div id="right">
        <p>{this.state.text}</p>               <-------------HERE
      </div>
    );
  }
}

export default Preview;

But when it is set in a variable before the return statement (i.e. const text = this.props.markdown) then call it in return via <p>{text}</p>. It will work. Even you don’t store it in a variable before the return statement but instead directly in the return statement (e.g. <p>{this.props.markdown}</p> it will work. My point is why it is not working when you set in a state?

class Preview extends Component {
  constructor(props) {
    super(props);
    this.state = {
      converter: new showdown.Converter()
    }
    this.createMarkup = this.createMarkup.bind(this);
  }

  createMarkup() {
    return {__html: this.state.converter.makeHtml()}
  }

  render() {
    const text = this.props.markdown;               <-------------HERE
    this.state.converter.setOption('tables', 'true');
    return (
      <div id="right">
        <p>{text}</p>               <-------------HERE
      </div>
    );
  }
}

export default Preview;


#2
constructor(props) {
   super(props);
   this.state = {
     text: this.props.markdown,               <-------------HERE
     converter: new showdown.Converter()
   }
   this.createMarkup = this.createMarkup.bind(this);
 }

Correct me if I’m wrong, but in the constructor, you don’t have this.props.markdown because this doesn’t exist yet - that’s what the constructor is constructing. I think you just refer to them as props.markdown as they were passed in.

If there is any doubt, I would put some console.log statements in there and see exactly what this.props and props are.

Let us know if that doesn’t work.