6

This is a snippet of my code in a component. I'm trying to make a component whose height will change when the prop changes. How to fix the error? Property 'style' does not exist on type 'MutableRefObject'

    const bottom = useRef(null)

    useEffect(() => {
        active ?
        bottom.style.maxHeight = '120px'
        :
        bottom.style.maxHeight = '0px'
    }, [active])

    return (
        <div ref={bottom}></div>
    )

3 Answers 3

2
 const bottom = useRef<HTMLDivElement>(null)
  useEffect(() => {
    if (bottom.current) {
      bottom.current.style.maxHeight = active ? '120px': '0'
    }
  }, [active])
  • You need to specify the element type in your useRef
  • You need to use bottom.current
  • I'm not sure you can make assignments in a ternary
Sign up to request clarification or add additional context in comments.

Comments

2

Okay. I made 2 mistakes in my code, because of which it did not work. I'm still a beginner typescript developer. Final version of my code:

const bottom = useRef<HTMLDivElement>(null)

useEffect(() => {
    if (bottom.current) {
        active ?
        bottom.current.style.maxHeight = bottom.current.scrollHeight + 'px'
        :
        bottom.current.style.maxHeight = '0px'
    }
}, [active])

return (
    <div ref={bottom}></div>
)

1 Comment

No, the use of any is not a solution, it disables typescript.
0

Updated for Tailwind based on OP's comment

Since Tailwind supports dynamic classnames you can set the className based on a state variable.

So you could have active be a state variable like this:

  const [active, setActive] = useState(false);

And then your div can have it's maxHeight set based on the active variable:

      <div
        className={`transition ${active ? "max-h-[10px]" : "max-h-[30px]"}`}
      />

You don't need to directly manipulate the DOM

Many of the other answer suggested using refs to directly manipulate the DOM, but this is really not the React way to approach this. You should (almost) never need to directly manipulate the DOM and this case is no exception.

2 Comments

In this project, I am using Tailwind CSS. It was important for me to achieve a smooth disclosure of the element. I wrote 120 pixels just for example. In my solution you can see a little hack - bottom.current.style.maxHeight = bottom.current.scrollHeight + 'px'. But your solution is good too, thanks for the help!
@IvanStepin I updated my answer to directly address Tailwind. Using a ref for this is probably not ideal since refs should be treated as an escape hatch from React.

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.