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

importLoginfrom'./Login'importHomefrom'./Home'constApp = ({ user }) => (
  <Body>
    {user.loggedIn ? <Routepath="/"component={Home} /> : <Redirectto="/login" />}
    <Routepath="/login"component={Login} /></Body>
)

With code splitting:

importAsyncfrom'react-code-splitting'importLoginfrom'./Login'constHome = () => <Asyncload={import('./Home')} />constLostPassword = props => <Asyncload={import('./LostPassword')} componentProps={props}/>constApp = ({ user }) => (
  <Body>
    {user.loggedIn ? <Routepath="/"component={Home} /> : <Redirectto="/login" />}
    <Routepath="/login"component={Login} /><Routepath="/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

importReact, { Component } from'react';
importScriptTagfrom'react-script-tag';

classDemoextendsComponent {

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

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