Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React: how to set `dagerouslySetInnerHTML` from component's state?

I’m new to React and am working on an already-existing component that seems a bit old.

I have a label element I want to set dynamically, depending on state. To this affect I have:

export default class Address extends React.Component {
 // Props and other handlers

    componentTitle() {
        if (this.state.isPostal) {
            return this.state.labels.PostalAddressLabel
        }
        else {
            return this.state.labels.StreetAddressLabel
        }
    };

   render() {
      return (
        <div className="block">
            <div className="grid-x">
                <div className="input-field cell">
                    <label 
                        dangerouslySetInnerHTML={{ __html: componentTitle() }} 
                    />

        // Other elements
   }
}

However, this does not work. I get the error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught ReferenceError: componentTitle is not defined

I’ve tried various combination of this including

  • Using a var const compTitle = componentTitle() {

  • placing the function within the render() function

  • And removing the function altogether and putting the if/else condition in the render() function, eg:

     if (this.state.isPostal) {
       const compTitle = this.state.labels.PostalAddressLabel
         }
     else {
       const compTitle = this.state.labels.StreetAddressLabel
     }
    
     return (
         <div className="block">
             <div className="grid-x">
                 <div className="input-field cell">
                     <label 
                         dangerouslySetInnerHTML={{ __html: compTitle }} 
    

But I just can’t get it to work.

Could anyone point me in the right direction?

>Solution :

use this keyword this.componentTitle()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading