2

I would like to add React component into the string as JSX like this

const name = <a href="#"> World </a>
const a = 'Hello, {name}'
return <div>{a}</div>

how can I get the following output

<div> Hello, <a href="#">World</a></div>
1
  • @Rustam D9RS's answer below is great, but unless you're doing anything particularly complex with your assignment to JSX, something like this is usually simpler: const name = 'World'; const href='#'; return <div><a href={href}>{name}</a></div> Commented Jun 18, 2020 at 8:33

2 Answers 2

2

You don't need a string; instead, you also need to use JSX syntax (this won't work with a string):

const name = <a href="/">World</a>;
const a = <>Hello, {name}</>;
return <div>{a}</div>;
Sign up to request clarification or add additional context in comments.

Comments

1

you can just use another function component to get the other HTML part, and then add it to the main app return function inside {}, here is a working snippet:

function name() { 
  return (<a href="#"> World </a>);
}

const App = () => {
  const a = `Hello, `
  return (
    <div>{a} {name()}</div>
  );
};

ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

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.