Search code examples
react-nativeonpress

How to cross out text with onpress clickHandler


I am trying to have a button cross out text with 'line-through'. I am not sure how to connect this to the button.

'''

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function App() {
  const [name, setName] = useState('shaun')

  const clickHandler = () => {
    setName('shaun (CROSSED OUT)');
  }

  return (
    <View style={styles.container}>
      <Text>My name is {name}</Text>
      <Text></Text>
      <View style={styles.buttonContainer}>
        <Button title='update state' onPress={clickHandler} />
      </View>
    </View>
  );
}

Solution

  • You can use a state variable to keep track of it.

    quick example -

    import React, { useState } from 'react';
    import { StyleSheet, Text, View, Button } from 'react-native';
    
    export default function App() {
      const [name, setName] = useState('shaun')
      const [crossedOut, setCrossedOut] = useState(false) // extra state variable
    
      const clickHandler = () => {
        setName('shaun (CROSSED OUT)');
        setCrossedOut(true) // set it to true on click
      }
    
      return (
        <View style={styles.container}>
          {/* apply style only if crossedOut is true */}
          <Text style={crossedOut && {textDecorationLine: 'line-through'}}>My name is {name}</Text> 
          <View style={styles.buttonContainer}>
            <Button title='update state' onPress={clickHandler} />
          </View>
        </View>
      );
    }