Using useState to edit the style of a Component in React Native
Jay Vijay Modi
Posted on August 8, 2021
I am new to using state management and was finding difficulty editing styles of a component using useState. Currently I have a swiper component that holds my main images and below that I have a thumbnail gallery for each of those images with a borderWidth:1
. What I want is that only the border for the current slide should be active while the others show no borderWidth. Currently my display looks like this where all the thumbnails have a border:
export default function App() {
const [activeBorder, setActiveBorder] = useState();
const [activeIndex, setActiveIndex] = useState();
const fishMapping = ["Fish Azure", "Fish Salmon", "Fish Another"];
const onIndexChanged = (index) => setActiveIndex(index);
return (
<View style={{ flex: 1 }}>
<ImageBackground
style={globalStyles.backgroundImage}
source={require('./resource/images/bg1080.jpeg')}
>
<Fish onIndexChanged={onIndexChanged}/>
<BottomImages />
{ activeIndex && <Text>`Fish` ${fishMapping[activeIndex]}</Text> }
</ImageBackground>
</View>
);
}
And for the thumbnails below this is my code:
BottomImages.js:
export default class BottomImages extends Component {
state = {
columns: 3,
};
render() {
const { columns } = this.state;
return (
<View style={styles.container}>
<FlatList
numColumns={columns}
data={[
require('../resource/images/AzureDamsel.png'),
require('../resource/images/BicolourAngelfish.png'),
require('../resource/images/ClownTriggerfish.png'),
]}
renderItem={({ item }) => {
return (
<ListItem
itemWidth={(ITEM_WIDTH - 10 * columns) / columns}
image={item}
/>
);
}}
keyExtractor={(index) => {
return index;
}}
/>
</View>
);
}
}
ListItem.js which holds my thumbnail images as well as the borderbox for the images:
const ListItem = (props) => {
const { itemWidth } = props;
return (
<TouchableWithoutFeedback>
<Animated.View
style={{
margin: 5,
}}>
<Image
style={{
width: itemWidth,
height: 50,
borderWidth: 1,
borderColor: '#000',
}}
source={props.image}></Image>
</Animated.View>
</TouchableWithoutFeedback>
);
};
Here's a link to the snack just in case: Sandbox
Posted on August 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024