Home > Mobile >  TypeScript with React. Property 'style' does not exist on type 'MutableRefObject<n
TypeScript with React. Property 'style' does not exist on type 'MutableRefObject<n

Time:08-25

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>
    )

CodePudding user response:

 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

CodePudding user response:

This is actually even simpler than you would expect.

You can set styles using the styles prop and those can by dynamic based on variables.

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
        style={{
          backgroundColor: "blue",
          width: 300,
          height: 300,
          maxHeight: active ? 10 : 300
        }}
      />

CodePudding user response:

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>
)
  • Related