Reputation: 188
So I'm using React Native+Expo and I made a custom component that's a stepper.
Looks like this:
This is the code for it:
import React, { useState } from 'react';
import { View, Text,StyleSheet, TouchableOpacity } from 'react-native';
const Stepper = (props) => {
let counter = 0;
const increment = () => {
counter += 1
}
const decrement = () => {
counter -= 1
}
return (
<View style={{ ...styles.stepperStyle, ...props.containerStyle }}>
<TouchableOpacity style={{
backgroundColor: props.leftColor,
flex: 1,
alignItems: 'center',
justifyContent: 'center',
borderTopLeftRadius: props.radius,
borderBottomLeftRadius: props.radius
}}>
<Text adjustsFontSizeToFit={true} style={{ fontSize: 40 }}>-</Text>
</TouchableOpacity>
<View style={{
borderLeftWidth: 1,
borderRightWidth: 1,
alignItems: 'center',
justifyContent: 'center',
flex: 1
}}>
<Text style={props.labelStyle}>{props.initialValue} {props.label}</Text>
</View>
<TouchableOpacity style={{
backgroundColor: props.rightColor,
flex: 1,
alignItems: 'center',
justifyContent: 'center',
borderTopRightRadius: props.radius,
borderBottomRightRadius: props.radius
}}>
<Text adjustsFontSizeToFit={true}
style={{ fontSize: 40 }}>+</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
stepperStyle: {
backgroundColor: 'transparent',
flexDirection: 'row',
borderRadius: 100,
borderWidth: 1,
width: '100%',
height: 42
}
});
export default Stepper
What I want to do is make some sort of event listener or function that can return the counter value whenever it has changed.
So from the outside, I'd want it to look like this:
<Stepper
onValueChange={count => setSets(count)}
/>
I'm new to doing something like this. Would I need to use the useEffect hook? What would be the best way to just get the current counter value? Any help would be appreciated!
Upvotes: 1
Views: 1217
Reputation: 371168
Since it looks like you want the value inside the component to match the stateful sets
value outside the component, the most reasonable way to handle this would be to pass both the sets
and setSets
down as props, and use and call those through increment
and decrement
.
<Stepper
{...{ sets, setSets }}
/>
const Stepper = ({ sets, setSets }) => {
const increment = () => setSets(sets + 1);
const decrement = () => setSets(sets - 1);
// other code that references increment and decrement and sets
If the outer state name can change, use
<Stepper
counter={sets} setCounter={setSets}
/>
const Stepper = ({ counter, setCounter }) => {
const increment = () => setCounter(counter + 1);
const decrement = () => setCounter(counter - 1);
// other code that references increment and decrement and counter
Upvotes: 2