How to add <script> tag using ReactJS?

I need to declare a javascript function as described below:

render: function() { return ( <div> <SomeReactClass somefunction="myFunction"> <script> function myFunction(index, row) { return index; <<<< error in this line } </script> </div> ); } 

But it does not compile: "Parse error: line 113: unexpected token return"

How to add a tag using ReactJS?


UPDATE

I am trying to use a detailed view of the boot table . The function is passed as a parameter to the grid and is used to visualize the detail of the string. Also, see the source code example for a better understanding.

When I try, as you say, it compiles, but does not work at all:

Here's what it looks like (in the example above):

enter image description here

This is what I get with <SomeReactClass somefunction={myFunction}>

enter image description here

+7
javascript reactjs
source share
3 answers

I know this is old, but I came across this recently, and here is the best solution I have found (I use it for browser polyprofiles, but it works for any code):

 render: function() { return ( <div> <SomeReactClass somefunction="myFunction"> <script dangerouslySetInnerHTML={{ __html: `function myFunction(index, row) {return index;}` }} /> </div> ); } 
+3
source share

Inside JSX {...} stands for JavaScript expression. return index; per se is not a valid expression.

You must explicitly create a string so that {...} not interpreted by JSX. Template literals may be the easiest solution:

 <script>{` function myFunction(index, row) { return index; } `}</script> 

However, it’s hard for me to find the reason why you would like to dynamically create <script> .


What you should probably do is pass the function directly to the component:

 function myFunction(index, row) { return index; } var Component = React.createElement({ render: function() { return ( <div> <SomeReactClass somefunction={myFunction} /> </div> ); } }); 

But it’s hard to say if you don’t explain what you are really trying to achieve here.

+2
source share

I think you're just looking for interpolation of your JS

 function myFunction(index, row) { return index; } render: function() { return ( <div> <SomeReactClass somefunction={myFunction}> </div> ); } 

to interpolate javascript in jsx use curly braces {}
https://facebook.imtqy.com/react/docs/jsx-in-depth.html#javascript-expressions

for your editing:
again, you need to use curly braces to interpolate your function. so inside SomeReactClass you need to do something similar in the render function:

 <div>{this.props.myFunction(index, row)}</div> 

First of all, you need to not only interpolate this function, but also perform it.

+1
source share

All Articles