0

Today i want to create something like form in react native that looks like enter image description here

It's pretty simple. i used this lib for radio button. However i want to change this text in the button when i click button next. I used following code.

import React, { useState, useRef } from "react";
import { StyleSheet, View, Button } from "react-native";
import RadioButtonRN from "radio-buttons-react-native";

export default function App() {
  const numRef = useRef(0);
  const questions = [
    {
      question: "What is localhost's IP address?",
      answers: [
        { id: "1", text: "192.168.1.1" },
        { id: "2", text: "127.0.0.1", correct: true },
        { id: "3", text: "209.85.231.104" },
        { id: "4", text: "66.220.149.25" },
      ],
    },
    {
      question: "What kind of11 fruit was used to name a computer in 1984?",
      answers: [
        { id: "1", text: "Blackberry" },
        { id: "2", text: "Blueberry" },
        { id: "3", text: "Pear" },
        { id: "4", text: "Apple", correct: true },
      ],
    },
  ];

  return (
    <View>
      <RadioButtonRN
        data={questions[numRef.current].answers.map((item) => ({
          label: item.text,
          correct: item.correct,
        }))}
        selectedBtn={(e) => {
          console.log(e);
        }}
      />
      <Button
        title="Next"
        onPress={() => {
          numRef.current = numRef.current + 1;
        }}
      />
    </View>
  );
}

So right now when i clicked on the next button, the only thing thats updated is variable

numRef

But questions[numRef.current] doesn't update text in the button.

How can i fix that?

1 Answer 1

1

Changing the value of a ref doesn't result in a re-render. For data that, when it gets changed, should result in a re-render, you should use state instead.

export default function App() {
    const [num, setNum] = useState(0);
    // ...

    data={questions[num].answers.map((item) => ({

    // ...

    onPress={() => {
        setNum(num + 1)l
    }}
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly. Thank you. So for re-rander data i should use useState instead of useref
Yes, you should usually be using state by default in React. Refs are less common, and are more for when state just doesn't solve the problem.

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.