Andre Thonas
Andre Thonas

Reputation: 311

How to extend input component functionality

I have an input component in react that receives an onChange event from another component:

<input type="text" onChange={onChange} />

But I want to add a prop from another component to this component which makes the input only accept alphabets.

it would be something like this:

<input type="text" onKeyPress={ /* return true or false */ } />

But how can I use them both together?

const InputComponent = ({ onchange, value, alphabetOnly }) => {
  const handleKeyPress = e => {
    let alphabet =
      (e.charCode > 64 && e.charCode < 91) ||
      (e.charCode > 96 && e.charCode < 123);

    if (alphabet) {
      return true;
    }

    console.log("stop user from entering that char");

    return false;
  };

  return (
    <input
      onKeyPress={handleKeyPress}
      onChange={onchange}
      value={value}
    />
  );
};

export default function App() {
  const [value, setValue] = useState("");

  const handleChange = e => setValue(e.target.value);

  return (
    <div className="App">
      <InputComponent onchange={handleChange} value={value} />
    </div>
  );
}

CodeSandbox: https://codesandbox.io/s/distracted-cannon-6ueko

Upvotes: 1

Views: 241

Answers (3)

gdh
gdh

Reputation: 13692

Instead of onKeyPress add a validation condition inside onChange. Update the state value only only when the value is an alphabet and alphabetOnly prop is true. You can use string.chatCodeAt function to check if the value is an alphabet.

Working demo

Code Snippet

const InputComponent = ({ onchange, value, alphabetOnly }) => {
  const handleChange = e => {
    const val = e.target.value;
    if (alphabetOnly) {
      let alphabet =
        (val.charCodeAt(val.length - 1) > 64 &&
          val.charCodeAt(val.length - 1) < 91) ||
        (val.charCodeAt(val.length - 1) > 96 &&
          val.charCodeAt(val.length - 1) < 123) ||
        val === "";
      if (alphabet) {
        onchange(val);
      }
    } else {
      onchange(val);
    }
  };

  return <input onChange={handleChange} value={value} />;
};

export default function App() {
  const [value, setValue] = useState("");

  const handleChange = val => setValue(val);

  return (
    <div className="App">
      <InputComponent alphabetOnly onchange={handleChange} value={value} />
    </div>
  );
}

Upvotes: 1

gamini2006
gamini2006

Reputation: 299

You can use the 'onChange' function to validate inputs

onChange(event){
  .....
  validatInput(event.charCode)// your inpul validation logic function
  .....
}

Upvotes: 0

Celso Wellington
Celso Wellington

Reputation: 889

event.target.value.charCodeAt(0) may solve your issue (it will read the first character from user input and return the keyCode relative to it).

keep in mind that users may still paste the input, so if the alphabet filter pass, make sure to add only the first character of the input string (event.target.value[0]).

Upvotes: 0

Related Questions