Search code examples
reactjsreact-nativetextinput

How to change the border colour 'onChangeText' in TextInput Component


So, I was trying to make this nice little TextInput Component where the border colour changes as soon as I start typing and if I clear the text border colour returns to default.


Solution

  • Here is the Component TextInput. When you write in the textbox, border colour of the textbox will be changed and after clearing text it sets default. Please write a small css class .myInput which I wrote in TextInput.css

    import React, {useEffect, useState} from 'react'
    import './TextInput.css'
    
    function TextInput(props) {
        const [style, setStyle] = useState({});
    
        function textChange(e) {
            if(e.target.value === '')
                setStyle({border: '1px solid gray'});
            else
                setStyle({border: '1px solid red'});
        }
        return (
            <div>
                <input className="myInput" style={style} onChange={textChange} type="text"/>
            </div>
        );
    }
    
    export default TextInput;
    

    Here is the css class:

    .myInput {    
       outline-width: 0; 
    }