Reputation: 1
I have a list with some items that are added to a state on click, Im using native-base, how can I change the style of the listitem when I press it, or add the "selected" attribute to the list item?
code
const [data, setData] = useState([]);
const _renderItem = ({ item, index }) => {
return (
<ListItem
button={true}
onPress={() => handleItemSelect(item)}
>
<Left>
<Text>{item.Name}</Text>
</Left>
<Right>
<Icon name="add" style={{ paddingHorizontal: 5 }} />
</Right>
</ListItem>
);
};
return(
<Container>
<List>
<FlatList
data={data}
renderItem={_renderItem}
/>
</List>
</Container>
);
Im wondering how am I going to add a style and distinguish between the different list items that I have, if this isn't possible how can I use native-base "selected" and append it to the listitem?
the handleItemSelect adds the item id to a state so im currently managing which items are selected, how can I use this info, or any other way to highlight the selected items?
Edit: I figured how to easily do this since I have the selected items id's
<ListItem
selected={selectedItems.some((prevItem) => prevItem._id === item._id)}
style={sameasabove ? style1 : style2}
button={true}
onPress={() => handleItemSelect(item)}
>
</ListItem>
Upvotes: 0
Views: 759
Reputation: 4201
You can do some thing like this:
Example
export default class App extends React.Component {
constructor() {
super();
this.state = {
data: [
{ name: "Interstellar" },
{ name: "Dark Knight" },
{ name: "Pop" },
{ name: "Pulp Fiction" },
{ name: "Burning Train" },
],
setData: []
};
for (var i = 0; i < this.state.data.length; i++) {
this.state.setData[i] = "red";
}
this.setState({
setData: this.state.setData
})
}
handleItemSelect(item, index) {
this.state.setData[index] = "green";
this.setState({
setData: this.state.setData
})
}
renderItem = ({ item, index }) => {
return (
<ListItem button={true}
onPress={() => this.handleItemSelect(item, index)} style={{ marginLeft: 0 }}>
<Body>
<Text style={{ color: this.state.setData[index] }}>{item.name}</Text>
</Body>
</ListItem>
);
};
render() {
return (
<FlatList style={{ marginTop: 30 }}
data={this.state.data}
renderItem={this.renderItem}
/>
);
}
}
You can set a color to your ListItem initially and then you can change the color on a click event.
Hope this helps!
Upvotes: 1