How to toggle the status of only one item in Flatlist?

Asked

Viewed 213 times

1

I have the following code:

const Sounds: React.FC = () => {
  const [hasSelect, setHasSelect] = useState(false);

  return (
    <Container>
      <FlatList
        data={data}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
        <Sound key={item.id} activeOpacity={0.7}>
          <MusicPic source={mushroom} />

    
          <AddSound onPress={() => setHasSelect(true)}>
            <ICon name="library-plus" color={hasSelect ? main : lighter} />
          </AddSound>
        </Sound>
        )}
      />
    </Container>

I’m trying to change the icon color when the user clicks on it, but all Flatlist icons have the status changed, as I do to change only the pressed?

  • You want to select one at a time or can more than one be selected at the same time?

  • Who would need to control that state is the <Sound>, nay <Sounds>... Or else it would control <Sounds> but through a Boolean/object array, not a single Boolean

  • Thanks Rafael, I created a separate component for each Sound and I passed the props for this component there and everything worked out, thank you very much

1 answer

3


I managed to solve, just create a separate component and call this component in the render of the flatlist by passing the props

Flatlist:

const Sounds: React.FC = () => {
  return (
    <Container>
      <TitleContainer>
        <Title>Biblioteca</Title>
      </TitleContainer>

      <FlatList
        data={data}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <Track
            id={item.id}
            source={item.image}
            music={item.music}
            artist={item.artist}
          />
        )}
      />
    </Container>
  );
}

Sound Componente:

function Track({ id, image, music, artist}: propsTypes) {
  const { main, lighter } = useContext(ThemeContext);
  const [hasSelect, setHasSelect] = useState(false);

  return (
    <Container key={id} activeOpacity={0.7}>
      <MusicPic source={image} />

      <InfoContainer>
        <Music>{music}</Music>
        <Artist>{artist}</Artist>
      </InfoContainer>

      <AddSound onPress={() => setHasSelect(true)}>
        <MaterialCommunityIcons name="library-plus" color={hasSelect ? main : lighter} />
      </AddSound>
    </Container>
  );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.