Skip to content Skip to sidebar Skip to footer

How To Add Script Tag In React/JSX File?

I want to use inline scripting to a React component. I am trying like this. What should be my approach? I could not find much information. I want to load the script when this comp

Solution 1:

What you need to do is codesplitting.

Without code splitting

+ are loaded at the first start

import Login from './Login'
import Home from './Home'

const App = ({ user }) => (
  <Body>
    {user.loggedIn ? <Route path="/" component={Home} /> : <Redirect to="/login" />}
    <Route path="/login" component={Login} />
  </Body>
)

With code splitting:

import Async from 'react-code-splitting'

import Login from './Login'
const Home = () => <Async load={import('./Home')} />
const LostPassword = props => <Async load={import('./LostPassword')} componentProps={props}/>

const App = ({ user }) => (
  <Body>
    {user.loggedIn ? <Route path="/" component={Home} /> : <Redirect to="/login" />}
    <Route path="/login" component={Login} />
    <Route path="/lostpassword" component={LostPassword} />
  </Body>
)

There are several ways of doing this, for example: https://github.com/didierfranc/react-code-splitting


Solution 2:

Use import or require on the top on a given js file for adding custom scripts or custom css, but I agree that you should review it to be sure everything behaves as you expect.

Example:

import "../../assets/js/extensions/mouse-gesture/options.js";

Or if you want to import a script only when using a method:

myMethod() {
  require("../../assets/js/extensions/mouse-gesture/options.js");
  ...
}

Solution 3:

You can try this library: npm install --save react-script-tag

https://www.npmjs.com/package/react-script-tag

import React, { Component } from 'react';
import ScriptTag from 'react-script-tag';

class Demo extends Component {

    render() {
        return (<ScriptTag isHydrating={true} type="text/javascript" src="some_script.js" />);
    }
}

Post a Comment for "How To Add Script Tag In React/JSX File?"