0

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";

1 Answer 1

1

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>
)
Sign up to request clarification or add additional context in comments.

1 Comment

please look into the link I have provided I want to implement full javascript present in that codepen.

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.