Home > Back-end >  How to change props value in functional component on onPress
How to change props value in functional component on onPress

Time:12-24

I am using FlatList for data display and also use the component for display.

<FlatList
                  contentContainerStyle={{ paddingBottom: 50 }}
                  data={postList}
                  renderItem={renderItem}
                  keyExtractor={(item, index) => index.toString()}
                  refreshing={refreshing}
                  onRefresh={_onRefresh}
                />

const renderItem = (item) => {
      return(
        <FeedMainStoryCard
          feedTittle={item.item.feedTittle}
          feedimage={item.item.feedImage}
          isUserLike={item.item.isLike}
        />
      )
  }

And here is FeedMainStoryCard.js file

<TouchableOpacity
            onPress={onPressHeart}
          >
            <Ionicons name={props.isUserLike === true ? "ios-heart-sharp" : "ios-heart-outline"} />
          </TouchableOpacity>

So How to change the isUserLike value on OnPress method like true and false and then change in <Ionicons name={props.isUserLike === true ? "ios-heart-sharp" : "ios-heart-outline"} /> icon.

Please suggest any solutions.

CodePudding user response:

You should not be changing the prop thats passed. You should instead be using states - can read more into this here: https://github.com/uberVU/react-guide/blob/master/props-vs-state.md.

For example you can pass the prop into a useState and toggle this value:

const Liker = ({ isUserLiked }) => {
  const [isLiked, setIsLiked] = useState(isUserLiked);

  const _onPressHeart = () => setIsLiked(!isLiked);

  return (
    <TouchableOpacity onPress={_onPressHeart}>
      <Ionicons
        name={isLiked ? 'ios-heart-sharp' : 'ios-heart-outline'}
        size={30}
      />
    </TouchableOpacity>
  );
};

You can find the full working example here: https://snack.expo.dev/@tnr_c/liker

CodePudding user response:

If isUserLike is already a Boolean it would be enough with: prop.yourBoolean if you want to check its true otherwise:!prop.yourBoolean

1st: A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.

2nd: You can add it to the children state and update its value in:

  const [isUserLike, setIsuserLike] = useState(props.isUserLike);

  const onPressHeart = () => {
    setIsuserLike(!isUserLike);
  };

<TouchableOpacity
         onPress={onPressHeart}>
         <Ionicons name={isUserLike ? "ios-heart-sharp" : "ios-heart-outline"} />
</TouchableOpacity>

DEMO: codesandbox.io/s/boring-mcclintock-vhj4c?file=/src/App.js

You can find more info here: https://es.reactjs.org/docs/state-and-lifecycle.html

  • Related