VAIBHAV YADAV
VAIBHAV YADAV

Reputation: 23

How to access child views in React Native?

I am new to react native. I have used a Flat Grid and I want to access a Image component on click event. I want to update its image and I am unable to access that image tag. On click of gird item I want to update image src.

Scenario :-

I have got list of recipes and on click of these I want show them selected by making the Icon to tick.

below is Flat Grid I have used.

<FlatGrid
itemDimension={130}
items={this.state.recipie_listing}
renderItem={({ item, index }) => (
<TouchableOpacity               
onPress={() => this.AddRecipe(index, item.id)}>
<View>
<ImageBackground
style={{
height: 250,
width: "100%"
}}
  imageStyle={{ borderRadius: 10 }}
  source={{
  uri: item.image
 }}
>
<Icon
name={this.state.icon_name}
style={{
color: this.state.icon_color,
position: "absolute",
right: 2,
top: 2
}}
/>

<View
style={{
backgroundColor: "rgba(220, 222, 224, 0.8)",
height: 60,
width: "100%",
borderBottomEndRadius: 10,
borderBottomStartRadius: 10,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
position: "absolute",
bottom: 0 
}}
>
 <CustomText
style={{
marginStart: 10,
marginEnd: 5,
color: "white",
fontSize: 15,
fontWeight: "bold"
}}
>
 {item.name}
</CustomText>
</View>
</ImageBackground>
</View>
</TouchableOpacity>
)}
/>

Upvotes: 1

Views: 233

Answers (1)

Rajesh Bhartia
Rajesh Bhartia

Reputation: 758

At first, add a state variable like showImage to false and then

In AddRecipe method call the setState method and toggle the variable value and then where you want to load the image src add conditional rendering here is a code example

  state = { showImage : false}
  ------
  AddRecipe = () =>{
      this.setState({
         showImage:!this.state.showImage   
      })

  render(){
    return(
      ----------
     <ImageBackground
        style={{
        height: 250,
        width: "100%"
        }}
        imageStyle={{ borderRadius: 10 }}
        source={{
        uri: this.state.showImage === true ? src1 : src2 
        }}
      >
      ----------
     )

  }

I think that will help you as far as I understand your problem.

Upvotes: 1

Related Questions