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>
CodePudding user response:
You can't convert a html website to a react project. You can only create a new react project and recreate your site by adapting your code in the app file. To create a react app, you can use this website.
CodePudding user response:
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;