Radio button value not resetting

Viewed 79

I have a list of questions. And on click of next or previous I'm changing the question. I have 4 or 5 answers as radio buttons. I' using this package Radio button npm. And now I'm trying to change the question using states. I need the radio button unselected on changing of question. All content changing easily expect radio button resetting. Here is my code:-

               <ScrollView>
                 <RenderHtml
                    contentWidth={width}
                    source={{html:question}}
                 />
                 <OptionsView options={options} selectedBtn={(e) =>updateAnswer(e.option)}/>
                 
          </ScrollView>

Functional component

    const OptionsView=(props)=>{
   return(
      <RadioButtonRN
            style={{marginHorizontal:5,marginTop:1,margin:5}}
            deactiveColor={'gray'}
            activeColor={'green'}
            initial={0}
            boxStyle={{height:50}}
            data={props.options}
            icon={
               <Icon
                  name="check-circle"
                  size={25}
                  color="green"
               />
      }/>
)}
2 Answers

I solved it using below code:-

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

const App = () => {

  const [show,setShow] = React.useState(true);
  const data = [
  {
    label: 'data 1'
  },
  {
    label: 'data 2'
  }
  ];

  React.useEffect(()=>{
    if(!show) setShow(true)
  },[show])

  const resetHandler = () =>{
    setShow(false)
  }


  return (
    <View style={styles.container}>
    {show && 
            <RadioButtonRN
          data={data}
          selectedBtn={(e) => console.log(e)}
        />
    }

        <Button title='reset' onPress={resetHandler}  />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
paddingTop:100,
  }
});

export default App;

Reference:- Radio Reset Button

If you are rendering your options base on the props that has been passed from parent component , U need to also include this hook in order to update your child component:

const OptionsView = (props.options) => {
    const [options, setOptions] = useState(props.options);

    useEffect(() => {
        setOptions(props.options)
      }, [props.options]

      return ( 
        <RadioButtonRN/>
      )
    }

Related