Render radio Buttons based on arrays

Asked

Viewed 26 times

-1

I am developing an online school evaluation. I get some questions and each question has several options for selection.

Need to show options like Radio Buttons, allowing user to select 1 option by question.

My Radio Button component is this: Radio Button

Opions consist of several arrays with the options of the questions, as the image below: Arrays de options

What happens is that the options are not appearing as they are in the arrays, on the screen are appearing as follows. inserir a descrição da imagem aqui

I understand that it is due to the fact that I am not doing the repetition loop correctly to get the content of these arrays, however, I would like to know which is the correct form.

The way I’m doing it is (complete code is in GIST) :

{options.map(option => (
  <label htmlFor={String(option.id)} key={option.id}>
    <input
      ref={ref => inputRefs.current.push(ref as HTMLInputElement)}
      type="radio"
      name={name}
      defaultChecked={defaultValue.includes(option.id)}
      value={option.option}
      {...rest}
    />
    {option.option}
  </label>
))}

Code where I call the radio button component and step options and name is in this GIST.

1 answer

1


For what you implied based on the image, options is an array of size 1 containing another array of size 4. Serial something like:

[[{id: 1, ...}, {id: 2, ...}, {id: 3, ...}, {id: 4, ...}]]

Then you should specify the first element in options.map(), thus:

{options[0].map(option => (
  <label htmlFor={String(option.id)} key={option.id}>
    <input
      ref={ref => inputRefs.current.push(ref as HTMLInputElement)}
      type="radio"
      name={name}
      defaultChecked={defaultValue.includes(option.id)}
      value={option.option}
      {...rest}
    />
    {option.option}
  </label>
))}

Did you try it this way? I’m assuming this based on the first image you showed from the console.log and that this refers to the options.

  • Right! I managed to solve some problems, now I have a problem with the typescript interfaces. I will edit the question.

  • 1

    Do not edit, ask another question with another topic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.