Home > OS >  Replace item in array react native
Replace item in array react native

Time:10-18

I'm new to js and react-native. I have buttons on my app to change the languages, one button "English" and one button "Français".

const langues = [
  {
    id:0,
    title: 'Français',
    selected: true
  },
  {
    id:1,
    title: 'English',
    selected: false
  }
];

function Settings() {
  return(
     <View>
         {langues.map(({title,selected}) => (
            <View>
               <Pressable style={styles.LanguesButton} >
                  {selected && <AntDesign size={15} name={'checkcircle'} /> }
                  <Text style={ {paddingLeft:selected ? 15 : 30} }>{title}</Text>
               </Pressable>
           </View>
         ))}
     </View>
   )
}

I would like to set selected to true for English, and false for Français when I click on "English" and same for "Français" but I don't understand how to do that.

PS: I already see that there are similar topics here but like I said I'm new to this language and I didn't understand the explanation on those topics ^^'.

CodePudding user response:

First you need to create a state object that tells react native to render whenever it is updated like so;

import { useState } from "react";
const [languages, setLanguages] = useState([
{
    id: 0,
    title: 'Français',
    selected: true
},
{
    id: 1,
    title: 'English',
    selected: false
}

]);

Then you render this list. Whenever you press any language, you modify the state by calling setLanguages function like so;

const onPressed = (title) => {
let temp = [...languages];
temp.forEach(lang => {
    if (lang.title == title) {
        lang.selected = true;
    }
    else {
        lang.selected = false;
    }
});
setLanguages(temp);

}

function Settings() {
    return (
        <View>
            {languages.map(({ title, selected }) => (
                <View>
                    <Pressable style={styles.LanguesButton} onPress={() => {
                        onPressed(title);
                    }}>
                    </Pressable>
                </View>
            ))}
        </View>
    )
}

After every press you will set the state and the screen will know that there has been a change and rerender.

CodePudding user response:

Through onPress and find, like:

<Pressable onPress={ () => 
langues.find(lang.title === title).selected = true}>

https://reactnative.dev/docs/pressable#onpress

  • Related