Akshit Kumar
Akshit Kumar

Reputation: 25

script tag not working with react site , when used in index.html

I was working on a hobby project in react, I want to implement something like this

but It won't work with me using the javascript(putting it in a script tag) in the index.html, I think it has something to do with the DOM, if you could explain what's going on here that would be nice.

document.getElementById('div1').style.visibility = "hidden";

Upvotes: 0

Views: 291

Answers (1)

TechyTech
TechyTech

Reputation: 497

Most likely you'd want to instead use hooks to accomplish things involving changing element state. Specifically, you could use a piece of dynamic state with the useState hook to control that div's visibility. For example:

const [divVisibility, setDivVisibility] = useState("visible");

// Some function that updates the visibility
const someFunction = () => {
  setDivVisiblity("hidden");
}

return (
  <div style={{ visibility: divVisibility }}>
    ...
  </div>
)

Alternatively, if you really want to access the HTML element object within a React component (which typically is less recommended other than for specific use cases, which perhaps yours would be), you could use the useRef hook. This gives you a "ref", aka a reference, to the underlying HTML element. This might look something like this:

const divRef = useRef();

// Some function that updates the visibility
const someFunction = () => {
  if (divRef.current) {
    divRef.current.style.visibility = "hidden";
  }
}

return (
  <div ref={divRef}>
    ...
  </div>
)

Upvotes: 1

Related Questions