Courtney
Courtney

Reputation: 339

React style object not being applied

Having issues with React style not being applied. I have no idea why it is not working as it was before.

See code below:

Accordion.js

import React, {useState} from 'react'

import { risk_assessment } from '../data/questions';

import AccordionItem from '../components/AccordionItem';
import Question from '../components/Question';


const Accordion = props => {
    const [active, setActive] = useState("0")
    
    return (
      <ul className="accordion">
        {risk_assessment.map((question, index) => (
          <AccordionItem 
            key={index}
            itemTitle={question.question}
            itemContent={<Question options={question.options} name={question.name} />} 
            toggle={() => setActive(index)} 
            active={active == index} />
        ))}
      </ul>
    )
}

export default Accordion

AccordionItem.js

import React, {useRef, useEffect} from 'react'

const AccordionItem = ({ itemTitle, itemContent, toggle, active }) => {
    const accordionContent = useRef()
    let contentHeight = {}
    useEffect(() => {
        contentHeight = active ? {height: accordionContent.current.scrollHeight} : {height: "0px"}
    })

    return (
        <li className="accordion_item">
            <button className="button" onClick={toggle}>
                {itemTitle}
                <span className="control">{active ? "—" : "+"}</span>
            </button>
            <div className="answer_wrapper" ref={accordionContent} style={contentHeight} >
                <div className="answer">{itemContent}</div>
            </div>
        </li>
    )
}

export default AccordionItem

Question.js simply renders the data inside the Accordion Item.

Here is the output from Chrome developer tools. Chrome Developer Tools Output

I have tried messing with the useEffect hook to no success. Changed it to run on every render, only on the first render, added the ref as a dependency etc.

I need to use the useRef hook to get the height of the content area dynamically.

Any help would be appreciated.

Upvotes: 0

Views: 239

Answers (1)

Kelvin
Kelvin

Reputation: 56

In your case when the component re-renders the value of your variable will be lost. Try putting contentHeight in a state.

  const [contentHeight, setContentHeight] = useState({})
    useEffect(() => {
      setContentHeight(active ? {height: accordionContent.current.scrollHeight} : {height: "0px"});
  }, [active])

You can find more information in this post.

Upvotes: 1

Related Questions