Reputation: 2959
Hello guys I've created a star rating component and now I've added it in my screen. My question now is how to I get the component return value inside my screen to send it to the server on submit.
This is my component
export default class StarsRating extends Component {
constructor(props) {
super(props)
this.state = {
rating: this.props.rating || null,
temp_rating: null
}
}
rate(rating) {
this.setState({
rating: rating,
temp_rating: rating
});
}
render() {
// This array will contain our star tags. We will include this
// array between the view tag.
let stars = [];
// Loop 5 times
for (var i = 1; i <= 5; i++) {
// Set the icon to filled stars
let icon = "star-outline";
// If ratings is lower, set the icon to unfilled stars
if (this.state.rating >= i && this.state.rating != null) {
icon = "star";
}
// Push the Icon tag in the stars array
stars.push((
<TouchableOpacity key={i} onPress={this.rate.bind(this, i)}>
<Icon
name={icon}
size={40}
color={colors.yellow}
/>
</TouchableOpacity >
));
}
return (
<View style={styles.wrapper}>
{stars}
</View>
);
}
}
and in my screen I access it like this <StarsRating />
Upvotes: 0
Views: 53
Reputation: 3812
Best option will be to pass onChanged
function as a prop to Your component from screen (where You render it).
<StarsRating onChanged={(rating) => {
// yourFunctionWithApiCall(rating)
// axios.post() directly here
}} />
In StarsRating
Component You just need to add call to this function in rate
method.
rate(rating) {
this.setState({
rating: rating,
temp_rating: rating
});
// when You think that value should be saved to API call function passed with props
this.props.onChanged(rating);
}
In general - pass this api communication function to your component as a props. Thanks to that You will can reuse it in another project when behaviour after rating change can be different.
Upvotes: 2