Search code examples
react-nativestylesheet

react native - update stylesheet value dynamically


I want to update stylesheet property "top" value. Which is currently "25" and I want to change the value to "0" or whatever. Actually, I want to archive once user click on the "TextInput" the "Text" will move little top of the "TextInput".

import React, {Component} from 'react';
import {View, Text, TextInput, StyleSheet } from 'react-native';

export default class InputBoxComponent extends Component{
  constructor(props){
    super(props);
    this.state = {
      'labelPosition':25
    }
  }

  onFoucusHandler = () => {
    this.state.labelPosition = 0
  }

  onBlurHandler = () => {
    this.state.labelPosition = 25
  }

  render(){
    return(
      <View style={styles.container}>
        <Text style={{
          'color':'#7b858e',
          'fontSize':12,
          'top':this.state.labelPosition
        }}>{this.props.label}</Text>
        <TextInput style={styles.input} onFocus={this.onFoucusHandler} onBlur={this.onBlurHandler}/>
      </View>
    )
  }
}

InputBoxComponent.defaultProps = {
  'label':'Label',
  'labelPosition': 25
}

const styles = StyleSheet.create({
  container:{
    paddingBottom: 10,
    paddingTop: 10
  },
  input:{
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    paddingTop: 5,
    paddingBottom: 5,
    fontSize: 16
  }
})

Solution

  • You can replace

    this.state.labelPosition = 0 
    

    with

    this.setState({labelPosition:0})
    

    Also have a look at library like Native Base https://docs.nativebase.io/Components.html#floating-label-headref I think floating label could do what you're trying to achieve.