Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Created January 6, 2017 15:38
Show Gist options
  • Select an option

  • Save davidsharp/0729be59b2b0ce1a4d2316847672cfd9 to your computer and use it in GitHub Desktop.

Select an option

Save davidsharp/0729be59b2b0ce1a4d2316847672cfd9 to your computer and use it in GitHub Desktop.
A pure React Native component for creating "radio button"-esque lists
/*
Used like:
<RadioList
radioOptions={ [
{value:5,label:"5 – blah blah blah"},
{value:4,label:"4 – bleh bleh bleh"},
{value:3,label:"3 – foo bar baz"},
{value:2,label:"2 – electric boogaloo"},
{value:1,label:"1 – jinkies"}
] }
onSelect={ option=>this.setState({option}) }
selected={ state.option }
renderRow={ / *optional* / renderRow }
/>
*/
import React, {Component} from 'react'
import {View, Text, ListView, TouchableWithoutFeedback} from 'react-native'
const RadioList = ({
radioOptions=[{value:undefined,label:'empty radio list'}],
onSelect=(_=>_),
selected=undefined,
renderRow=(
//If not using the default, you'll need to specify onSelect and selected specifically
({label,value/*,onSelect,selected*/})=>(<TouchableWithoutFeedback onPress={_=>onSelect(value)} key={value}>
<View><Text style={(selected===value ? { fontWeight: 'bold'} : {})}>
{label}
</Text></View>
</TouchableWithoutFeedback>)
)
}) => {
let dataSource = new ListView
.DataSource({rowHasChanged: ((r1, r2) => r1 !== r2)})
.cloneWithRows(radioOptions.map(c=>({onSelect,selected,...c})))
return (<ListView
scrollEnabled={ false }
dataSource={ dataSource }
renderRow={ renderRow }
/>)
}
export default RadioList
@davidsharp

Copy link
Copy Markdown
Author

It'd be nice to be more flexible about the list, but it keeps the <RadioList /> component quite clean without it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment