Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Custom TextInput Placeholder

I know you can dynamically change the Placeholder text and style, but can you create a custom Placeholder view all together?

This is what I'm trying to achieve:

enter image description here  

Is it possible to do something like this?

like image 874
Dror Bar Avatar asked Aug 09 '18 08:08

Dror Bar


2 Answers

I would suggest you to use custom style with the functional component.Create a functional component called RenderInput for which pass placeholder as props.

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

const RenderInput = ({ label , inputvalue,styleLabel, ipOnChangeText, placeholder}) => {
    const {inputStyle, labelStyle, containerStyle} = styles;
    return(
        <View style = {containerStyle}>
            <Text style= {styleLabel ? labelStyle : ""} >{label}</Text>
            <TextInput 
               autoCorrect={false}
               placeholder={placeholder}
               style= {inputStyle}
            />
        </View>
    );
 }

const styles ={
    inputStyle:{
        color: '#333',
        fontSize: 16,
        lineHeight: 23,  
        borderBottomColor: '#333',
        borderBottomWidth: 0.5,
        fontFamily: 'System',
    },
    labelStyle:{
        fontSize: 18,
        color: '#737373',
        paddingBottom: 10,
        fontFamily: 'System',
        position: 'relative',
        ':after': {
           content: '* ',
           position: absolute,
           left: 5,
           top: 0,
           color: '#bbb'
        }
    },
    containerStyle:{
        flexDirection: 'column',
        marginTop: 10,
        marginBottom: 10
    }
}
export { RenderInput };
like image 63
CodeZombie Avatar answered Sep 18 '22 18:09

CodeZombie


Creat a componet with name MyTextInput like this:

class MyTextInput extends Component {
  constructor(props) {
    super(props);
    this.state = { placeholder: props.text.length == 0 }
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(ev) {
    this.setState({ placeholder: ev.nativeEvent.text.length == 0 }); 
    this.props.onChange && this.props.onChange(ev); 
  }
  render() {
    const { placeholderStyle, style, onChange, ...rest } = this.props;

    return <TextInput 
      {...rest} 
      onChange={this.handleChange}
      style={this.state.placeholder ? [style, placeholderStyle] : style}
      />
  }
}

and use this in another component:

import MyTextInput from '.../MyTextInput';

<MyTextInput 
  text={this.state.myText}
  style={{ fontFamily: "Your Font" }}
  placeholderStyle={{ fontFamily: "AnotherFont", borderColor: 'red' }}
/>

you can custom any component you want with this way.

like image 30
Hoàng Vũ Anh Avatar answered Sep 17 '22 18:09

Hoàng Vũ Anh