Is it possible to send JSX tags from Nodejs(backend) to Reactjs?

Asked

Viewed 33 times

0

I need to send a data to the frontend, but I need it to be already with determinate tag around it, for example...

given backend: Name: Gabriel

I need you to get to the front this way:

<div>Gabriel</div>
  • why arrive a html ready on your front, already known the React does it for you? why do you want it so? complicate or lack of knowledge?

  • Why not just send the string "Gabriel" and React inside the desired element?

1 answer

0


Yes totally possible! in the backend you can work with json and send the data like this:

in Node we have a variable written with the name header:

const header = "<div><p>meu menu</p></div>"

The only thing we need to do is return to the front this variable:

Something to that effect:

return res.json({header})

and in the frontend we have to use in the React a famous guy: (dangerouslySetInnerHTML), famous for being considered dangerous rs but if you know how to use, no problem

function createMarkup() {
  // aqui você faz a request para o node e atribui ele a variavel header
  const {header} = request.get('header');
  return {__html: header};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

link to the documentation of React

Browser other questions tagged

You are not signed in. Login or sign up in order to post.