Home > Mobile >  React native onPress = change source code of image
React native onPress = change source code of image

Time:10-31

i have an array of objects in another file, i map that in 2 file how to do : e.target.src in react-native beacuse in react-native we dont have e

// store file:

export default [
        {
            liked: false,
        },
        { 
            liked: false,
        },
        {
            liked: false,
        },
        {
            liked: false,
        },
        
]

// 2 file

import images from 'store.js'

function unlike (){
// in react will be """ e.target.src = '../assets/unliked.png'  """  but how in react-native ?
}
function like (){
    // in react will be """ e.target.src = '../assets/liked.png' """ but how in react-native ?
}
return(
    <ScrollView>
                {images.map(image => {
                    return({image.liked ? <Image onPress={unlike} source={require('../assets/liked.png')} /> : <Image onPress={unlike} source={require('../assets/unliked.png')} />
              </ScrollView >
)

CodePudding user response:

You can import both images beforehand and dynamically set image source based on liked or not. To re-render the UI on each like or dislike use a state :

import images from 'store.js'
import React, { useState, useEffect } from 'react';
// other imports

const liked = require('../assets/liked.png')
const disliked = require('../assets/unliked.png')


const LikesComponent = (props) => {
  const [likesState, setLikesState] = useState(images)

  const handleLikes = (index) => {
    let temp = [...likesState]
    temp[index].liked = !temp[index].liked

    setLikesState(temp)
  }

  return(
    <ScrollView>
       {
       likesState.map((image, index) => <Image key={index} 
                                               source={image.liked ? liked : disliked} 
                                               onPress={() => handleLikes(index)} />
       }
    </ScrollView>
  )
}

export default LikesComponent
  • Related