Home > Software design >  How to show generalize function from Pressable in react-native
How to show generalize function from Pressable in react-native

Time:10-22

I am doing simple Android app that have to show content of variable on screen and I have component that appends string to existing variable. In function App I have:

export default function App() {
    const [getNumber, setNumber] = useState('');
    return (
        <>
            <View style={styles.numbers}>
                <Text>
                   {getNumber}
                </Text>
            </View>
            <Pressable style={styles.key} onPress={function(){
            setNumber(getNumber => getNumber   'addition');
            }}>
                <Text>Add</Text>
            </Pressable>
        ...
        </>
    );
}

This implementation works but when I try to extract and generalize function from Pressable

export default function App() {
    const [getNumber, setNumber] = useState('');

    funtion addString(stringToAdd){
        setNumber(getNumber   stringToAdd);
    }
    return(
        <>
        ...
            <Pressable style={styles.key} onPress={addNumber('addition')}>
                <Text>Add</Text>
            </Pressable>
        ...
        </>
    );
}

this does not work. It says i am re-rendering to React's limits.

I want to generalize because I have 12 Pressable. I am not into React and Javascript so I am missing something for sure.

CodePudding user response:

You are calling that addString right away and updating state when rendering the component. You can make it lazy by returning function that will do the updating.

function addString(stringToAdd) {
    return () => setNumber(number => number   stringToAdd);
}

CodePudding user response:

You are calling addString function directly on initialization in onPress method like

onPress={addString('addition')}

This will unnecessarily call the addString function on every re-render. Instead of calling it like that, do it like below

onPress={()=>addString('addition')}

Note the ()=>.

This will call the addString method only when the button is being pressed.

  • Related