Home > Mobile >  Change input mask based on selectedButton in React JS
Change input mask based on selectedButton in React JS

Time:12-03

I have some input masks on my code, a grid of buttons, and I have a state that stores which button is selected, and based on the selected button I want to change the mask applied to the input.

The state:

const [selectedButton, setSelectedButton] = React.useState("");

I've tried this:

const [input, setInput] = useMask(
    selectedButton === "Key1" ? maskOne : maskTwo
  );

It works perfectly! But only with 2 masks, I have 4 different masks, and I need some switch case type structure to choose which mask to apply

CodePudding user response:

Well, you more or less have suggested the solution already.

const [selectedButton, setSelectedButton] = React.useState("");

const returnMask = (button) => {
    switch (button) {
        case "Key1":
            return maskOne
        case "Key2":
            return maskTwo
        case "Key3":
            return maskThree
        case "Key4":
            return maskFour
        default:
            return maskOne
    }
}

const [input, setInput] = useMask(
    returnMask(selectedButton)
);

or if you can rename your masks or rename the values set to selectedButton you could simply reference the elements by value.

const [selectedButton, setSelectedButton] = React.useState("");

const [input, setInput] = useMask([selectedButton]); 
// Rename ether `Key1`, `Key2` to `maskOne` or `maskTwo`, or do it the opposite way (renaming the masks)
  • Related