Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
Force re-render React component when modified element HTML attribute

I have a button component rendered like below. I can't modify the button component itself but I can modify the parent component that renders it. I want to make it so that when I modify the button element's disabled attribute elsewhere in the code (that is modify the DOM like button.disabled = true) Given that I can't pass it from parent props, the button component gets re-rendered. I tried to use useRef and useEffect hook but it didn't work. I think I used them wrongly. Is there anyway I can achieve what I want?

  const elementRef = useRef()
  const [disabled, setDisabled] = useState(elementRef.current?.disabled)

  useEffect(() => {
    const buttonElement = elementRef.current
    buttonElement.addEventListener('disabled', handleDisabled)
  }, [elementRef.current])

  const handleDisabled = (e: any) => {
    setDisabled(e.target?.disabled)
  }

  return( <Button ref={elementRef} disabled={props.isDisabled || disabled}></Button> )
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You seemingly are working in two different "worlds": ReactJs and the DOM.

I suggest to use only React, and never modify any DOM properties directly.

You don't show how you want to change the disabled attribute/property "elsewhere in the code", but I assume you want to do something like

const setMyButtonDisabled = function(){
    document.querySelector('#myButton').disabled = true;
}

React is simply not able to know about this change. You have to tell React explicitly, like:

// not recommended:
const setMyButtonDisabled = function( setButtonDisabledCallback ){
    document.querySelector('#myButton').disabled = true;
    setButtonDisabledCallback( true );
}

And then find a way to pass the props around, so that the desired components have it (I can't know the relation between your code example and the "elsewhere").

But ideally you would never set the DOM buttonElements .disabled property, but set a React state buttonDisabled instead, and then just pass that around to where ever you need it:

// recommended:
const setMyButtonDisabled = function( setButtonDisabledCallback ){
    setButtonDisabledCallback( true );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!