Skip to content Skip to sidebar Skip to footer

Why Does My
Tag Show As An [object Object] When My Javascript Is Rendered?

I need to add break tags in between my sentences but when I do that I get [object Object] in place of a line break. Can someone please tell me how to fix this? const openingText =

Solution 1:

Because you can't add a string and an Object:

var tmp = {}
console.log('This is an object: ' + tmp)

What you want to do with React is:

const openingText = (
    <>
        We're happy to hear your project is underway.
        <br />
        You can review this business to tell others about your experience.
    </>
);

If you get an error using that syntax, you're probably on an older version of react or using a tool that doesn't support React Fragment short syntax, in which case you should be able to do:

const openingText = (
    <React.Fragment>
        We're happy to hear your project is underway.
        <br />
        You can review this business to tell others about your experience.
    </React.Fragment>
);

Solution 2:

You have to either use : dangerouslysetinnerhtml

classAppextendsReact.Component {

  render() {
    const str = 'We\'re happy to hear your project is underway.<br />You can review this business to tell others about your experience.';

    return ( 
      <divdangerouslySetInnerHTML = {{__html:str}} ></div>
    )
  }
}

ReactDOM.render( < App / > , document.querySelector("#app"))
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><divid="app"></div>

Or use template literals :

classAppextendsReact.Component {

  render() {
    const str = `We're happy to hear your project is underway.
You can review this business to tell others about your experience.`;

    return ( 
      <divstyle = {{whiteSpace: 'pre-line'}} > 
        {str} 
      </div>
    )
  }
}

ReactDOM.render( < App / > , document.querySelector("#app"))
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><divid="app"></div>

Post a Comment for "Why Does My
Tag Show As An [object Object] When My Javascript Is Rendered?"