Home > database >  How to change the colour of button according to number of characters in input field in react.js?
How to change the colour of button according to number of characters in input field in react.js?

Time:09-03

if number of characters in input field is less than 10 button should be disabled

if number of characters in input field is less than 20 background colour of button should be red

if number of characters in input field is more than 20 background colour of button should be green

export default function App() {
const [input, setInput] = useState("")

let inputLength;
const handleChange = (e) => {
setInput(e.target.value)
inputLength = e.target.value.length
console.log(inputLength)
}
return (
<div className="App">
 <h1>hello</h1>
 <button>Submit</button>
 <input value = {input} onChange = {handleChange}/>
</div>
);
}

CodePudding user response:

Maybe this code will help you.

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [input, setInput] = useState("");
  const [color, setColor] = useState("");

  let inputLength;
  const handleChange = (e) => {
    setInput(e.target.value);
    if (e.target.value.length > 10 && e.target.value.length < 20) {
      setColor("red");
    }
    if (e.target.value.length > 20) {
      setColor("green");
    }
    inputLength = e.target.value.length;
    console.log(inputLength);
  };
  return (
    <div className="App">
      <h1>hello</h1>
      <button
        style={{ background: color ? color : "" }}
        disabled={input.length < 10}
      >
        Submit
      </button>
      <input value={input} onChange={handleChange} />
    </div>
  );
}

Also here is demo https://codesandbox.io/s/eager-julien-vu6vkt?file=/src/App.js:0-769

CodePudding user response:

You can calculate the style of the button according to your input length like in my example with getButtonStyle. If you don't know how to change styles in react, please read this for more information on how it works: https://www.w3schools.com/react/react_css.asp Also if you feel like optimizing things you can read about useCallBack: https://reactjs.org/docs/hooks-reference.html#usecallback

export default App = () => {
    const [input, setInput] = useState("");

    const handleChange = (e) => {
        setInput(e.target.value);
    };

    const getButtonStyle = () => {
        const len = input.length;
        if (len <= 10) {
            return { disabled: true };
        } else if (len <= 20) {
            return { backgroundColor: "red" };
        }

        return { backgroundColor: "green" };
    };

    return (
        <div className="App">
            <h1>hello</h1>
            <button style={getButtonStyle()}>Submit</button>
            <input value={input} onChange={handleChange} />
        </div>
    );
};

  • Related