0

This might give a better idea, replace in paragraph, ' ==> " and highlight it

for (let i=0; i<orgString.length;i++) {
      changeVal.push("color:#" + Math.floor(Math.random() * 16777216).toString(16))
      let spanStart = <span style={changeVal[i]}> '"' </span>
      if (orgString.charAt[i] === "'") {
        let newSubstring = orgString.substring(0,orgString.charAt[i]);
        orgString = newSubstring + spanStart + orgString.substring(orgString.charAt[i+1], orgString.length);
      }
    }

Trying to change the multiple values, so concatenating in same string and render it once entire string is iterated

But getting output with [object Object] where concatenated HTML element

0

3 Answers 3

4

If the dynamic string to be concatenated is composed of text, use brackets inside of JSX:

const Snippet = () => {
  str = 'The world is new'

  return (<>
    {str}
    <p style={{ color: 'blue' }}>Every Morning</p>
  </>);
}

(also note that JSX elements styles' must be set with syntax like style={{ styleProp: stylePropVal }}, and you need to assign the function to a variable; const () => { will throw a syntax error)

Otherwise, you'll have to use dangerouslySetInnerHTML:

const Snippet = () => {
  const str = 'The world <b>is new</b>'
  return (<React.Fragment>
    <div dangerouslySetInnerHTML={{ __html: str }} />
    <p style={{ color: 'blue' }}> Every Morning</p>
  </React.Fragment>);
};

ReactDOM.render(<Snippet />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

But it'd be better to avoid that if at all possible - use text, state and JSX elements instead whenever you can.

Sign up to request clarification or add additional context in comments.

Comments

2

Simply Use React.Fragment:

const data = () => {
  str = 'The world is new'
  para = str + <p style='color:blue'> Every Morning</p>

return (
  <React.Fragment> 
    {para}
  </React.Fragment>
);
}

or

const data = () => {
  str = 'The world is new'
  para = str + <p style='color:blue'> Every Morning</p>

return (
  <> 
    {para}
  </>
);
}

Comments

0

I used this combination when mixing HTML tags with javascript variables

<li className="row"><strong> Alerts: </strong> <br/> {`${user.alerts}`} </li>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.