Home > database >  how to past object as child to script tag in react
how to past object as child to script tag in react

Time:01-25

i want to insert one html widget to my react app. On their site it looks like this

<script>{"fieldOne":"value"}</script>

and widget works if i past this straight to html.

But when i try to do it in react app it tells me: Parsing error: Unexpected token, expected "}"

CodePudding user response:

In JSX, { and } have a special meaning (wrapping JavaScript inside of the HTML/XML) so you need to have two { and two } to be able to have that:

<script>{{"fieldOne":"value"}}</script>

CodePudding user response:

The error message you're seeing is likely due to the fact that the JavaScript code within the <script> tag is not being properly executed within your React app.

One way to solve this issue is to use the dangerouslySetInnerHTML attribute on a React component, which allows you to pass raw HTML as a string to be rendered within the component.

Here's an example of how you can use this attribute to insert the widget in your React app:

import React from 'react';

const MyComponent = () => {
  const widgetHTML = "<script>{\"fieldOne\":\"value\"}</script>";

  return (
    <div dangerouslySetInnerHTML={{ __html: widgetHTML }} />
  );
};

export default MyComponent;

  • Related