Ad

How To Store Refs In Functional Component Properly

- 1 answer

I'm trying to create a component that tests english vocabulary.
Basically, there are 4 options with 1 correct.
When user chooses option, the right option is highlited in green, and the wrong one in red.
Then user can push the "next" button to go to the next batch of words.

I store refs in object (domRefs, line 68).
Populate it at line 80.
And remove all refs at line 115.
But it doesnt get removed, and leads to error (line 109)

https://stackblitz.com/edit/react-yocysc

So the question is - How to store these refs and what would be the better way to write this component?
Please help, Thanks.

Ad

Answer

You shouldn't keep refs for component in global variable, since it's making your component singleton. To apply some styles just use conditional rendering instead. Also, it's better to split your test app into several separate components with smaller responsibilities:

const getClassName(index, selected, rightAnswer) {
  if (selected === null) {
    return;
  }

  if (index === rightAnswer) {
    return classes.rightAnswer;
  }

  if (index === selected) {
    return classes.wrongAnswer;
  }
}
const Step = ({ question, answers, rightAnswer, selected, onSelect, onNext }) => (
  <div ...>
    <div>{ question }</div>
    { answers.map(
      (answer, index) => (
        <Paper
          key={ index }
          onClick={ () => onSelect(index) }
          className={ getClassName(index, selected, rightAnswer) } 
    ) }
    { selected && <button onClick={ onNext() }>Next</button> }
  </div>
);

const Test = () => {
  const [ index, setIndex ] = useState();
  const word = ..., answers = ..., onSelect = ..., onNext = ...,

  return (
    <Question
      question={ word }
      answers={ answers }
      ... />
  );
}
Ad
source: stackoverflow.com
Ad