I am pretty new to React and I wanted to try incorporating some pure Javascript in my React component. I have an html file of the script tags that I want to use which works, but obviously in React it is a little more complicated then just adding some script tags. From what I have been reading, it seems like I need to learn JSX. Either which way, here are snippets of the html code I want to use and then the React component I am trying to use it in.
HTML working code:
<!-- grabs foo element (list itself) and sets a timeout of 1 second so we can toggle off the hidden text class --> <script> const text = document.querySelector("#foo"); setTimeout(() => { text.classList.toggle("hidden-text"); }, 1000); </script> </body>
React Component:
import React from 'react'; import { Link } from 'react-router-dom'; import './HeroSec.css';`` /* Need to figure out how to use Javascript tags in React Component const Hello = () => { return React.createElement( 'script' ) }*/ function HeroSec(){ return( <div className='hero-container'>
Advertisement
Answer
The React Way
“I’m telling you Neo, when you use React properly, you won’t have to.” see code live here https://codesandbox.io/s/brave-bohr-vzp2h?file=/src/App.tsx
import { useEffect, setState } from 'react'; const App = () => { const [show, setShow] = useState(false); useEffect(() => { setTimeout(() => { setShow(true); }, 1000); }, []); return ( <div> <h1>My App</h1> {show ? <p>Hidden Text</p> : null} </div> ); }
So the idea is you focus on changing the logic of a single render pass rather than changing the particular DOM element. Focus on variable state and stop worrying about messing with DOM particulars. Calling setShow(true)
tells react to re-render the scene automatically.
I personally love these quick setup projects at codesandbox.io and encourage you to give it a try and avoid having to worry about setup to get comfortable first.
Here’s that example below and feel free to play with it.