0

I am a freshman of javascript and react. My question is: How to convert the following code to react code?

<div id="SOHUCS" sid="xxx"></div>
<script charset="utf-8" type="text/javascript" src="https://cy-cdn.kuaizhan.com/upload/changyan.js" ></script>
<script type="text/javascript">
window.changyan.api.config({
appid: 'xxx',
conf: 'xxxxx'
});
</script>

1 Answer 1

1

Using componentDidMount()

import React, {Component} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends Component {
    componentDidMount() {
        const script = document.createElement("script");
        script.async = true;
        script.src = "https://some-scripturl.js";
        this.div.appendChild(script);
    }
    render() {
        return ( <
            div className = "App"
            ref = {
                el => (this.div = el)
            } > < h1 > Hello react < /h1> {
                /* Script is inserted here */ } <
            /div>
        );
    }
}

export default App;

Using react-helmet

React helmet is an npm library that manages browser head manager, It is very easy to change web page lines of code inside a head tag. First, install react-helmet with the npm install command

npm install react-helmet

It adds the dependency to package.json

"dependencies": {
        "react-helmet": "^6.1.0",
}

Complete component code to add a script tag to component using react-helmet.

import React, { Component } from 'react';
import { Helmet } from 'react-helmet';

class AddingScriptExample extends Component {


    render() {
        return (
            <div className="application">
                <Helmet>
                    <script src="https://use.typekit.net/hello.js" type="text/javascript" />
                </Helmet>
            ...
            </div>
        );
    }
}
export default AddingScriptExample;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.