Search code examples
react-nativebuttoncolorsstylesonpress

Change a button color when textinput is null, by using onPress


I just started to learn React Native technology, so i try to change some lines in tutorial code. This is a form, which add new title, but I want to change color of button if value === "". I try to find, but mostly examples use classes, in this project I want to use functions

import React, { useState } from 'react'
import { View, StyleSheet, TextInput, Button, Alert } from 'react-native'

export const AddTodo = ({ onSubmit }) => {
  const [value, setValue] = useState('')

  const pressHandler = () => {
    if (value.trim()) {
      onSubmit(value)
      setValue('')
    } else {

      }
    }


  return (
    <View style={styles.block}>
      <TextInput
        style={styles.input}
        onChangeText={setValue}
        value={value}
        disabled
        placeholder='Введите название дела...'
        autoCorrect={false}
        autoCapitalize='none'
      />
      <Button title='Добавить' onPress={pressHandler} /> 
    </View>
  )
}

const styles = StyleSheet.create({
  block: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 15
  },
  input: {
    width: '70%',
    padding: 10,
    borderStyle: 'solid',
    borderBottomWidth: 2,
    borderBottomColor: '#3949ab'
  },
  button: {
    color: 'red'
  }
})

Solution

  • You use a controlled input field. You store the value in your state and you change it onChange with the input field. Next step is to set a style for your button depending on your current state.

    <TextInput
        style={[styles.input, value === '' ? styles.red : null]}
        onChangeText={setValue}
        value={value}
        disabled
        placeholder='Введите название дела...'
        autoCorrect={false}
        autoCapitalize='none'
      />
    

    In this case you need to add a style called "red" which changes the button color.

    red: {
      backgroundColor: 'red'
    }
    

    Something like this.

    Because your state is updated every time you change the input value, it gets updated onChange. If you want to set it on submit you need to add a isSubmitted boolean (default false ) to your state and set it to true in your pressHandler. You need to destructure isSubmitted in this example:

    style={[styles.input, value === '' && isSubmitted ? styles.red : null]}