1

Does anyone know how I can change the state of a renderItem when it leaves screen? Below I have the Flatlist with uses an Item, I want to change the state of the item once it exits the renderview.

const Item = memo(({content}) => {
  const [outOfView, setOutOfView] = useState(false)

  const onScroll= () => {
    if (!outOfView) setOutOfView(true) //Trying to get this to work
  }

  return (  
    <View style={styles.item} onScroll={onScroll}>
      <Text>{content.title}</Text>
    </View>
  )
})

const Slider = props => {
  const flatList = useRef()

  const _renderItem = ({ item, index }) => <Item content={item} />

  return (
    <View style={styles.container} >
      {props.header ? <AppText style={styles.header} text={props.header} /> : null}
      <FlatList
        data={props.data}
        horizontal
        pagingEnabled
        renderItem={_renderItem}
        keyExtractor={item => item._id}
        ref={flatList}
      />
    </View>
  )
}
Jat90
  • 493
  • 1
  • 10
  • 22
  • You can try using cleanup function in useEffect - https://elevateprogramming.blogspot.com/2022/09/react-code-snippets.html – Gaurav Gupta Sep 19 '22 at 18:32
  • Ignore previous one, i guess you need something like react-waypoint https://www.npmjs.com/package/react-waypoint https://elevateprogramming.blogspot.com/2022/09/react-code-snippets.html – Gaurav Gupta Sep 19 '22 at 18:38
  • I hope this link below helps you: https://stackoverflow.com/questions/45868284/how-to-get-currently-visible-index-in-rn-flat-list – F4RZ1N Sep 19 '22 at 19:08

1 Answers1

0

YOu can do something like this

import { useIsFocused } from '@react-navigation/native';

const Item = memo(({content}) => {
  const [outOfView, setOutOfView] = useState(false)

  const onScroll= () => {
    if (!outOfView) setOutOfView(true) //Trying to get this to work
  }

  const isFocused = useIsFocused();

  return (  
    <View style={styles.item} onScroll={onScroll}>
      <Text>{isFocused?content.title:"Offline"}</Text>
    </View>
  )
})

hope it helps. feel free for doubts

Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45
  • thanks but this shows the focused state of a 'screen' and not of a component, as per the docs: https://reactnavigation.org/docs/use-is-focused/ – Jat90 Sep 09 '22 at 10:41