How to replace the string in textbox when keyboard tab is pressed in react?

Viewed 26

in this text box when the user wants to type any name it should be converted to a specific pattern for example if the user types Text@1 in the console, I want to print $[Text@1]but notText@1$[Text@1] ,by clicking the keyboard tab button, I have tried e.keyCode===9 and [\t] by giving a condition but it is still not working, so how can I solve this issue?

import { useState } from "react";
export default function App() {
  const [value, setValue] = useState("");
  const handleChange = (e) => {
    setValue(e.target.value);
    e.target.value = e.target.value.replace(
      /[^A-Za-z0-9-\s!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g,
      `$[${value}]`
    );
    console.log(e.target.value);
  };

  return (
    <div className="App">
      <input
        value={value}
        onKeyPress={(e) => {
          if (e.target.value.length >= 15) e.preventDefault();
        }}
        placeholder="type value"
        onChange={handleChange}
      />
    </div>
  );
}
1 Answers

You're using controlled way to manage your input so that your input tag refers the state value but your event handler set the value before mutate it.

code sample
const handleChange = (e) => {
    const { value } = e.target
    const regex = /[^A-Za-z0-9-\s!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g
    const newValue = value.replace(regex, `$[${value}]`)
    setValue(newValue);
    console.log({ value, newValue })
  };
Related