Search code examples
htmlcssreactjschakra-ui

How to remove input default zero value when onChange?


I use chakra-ui input

https://chakra-ui.com/docs/components/input/usage

import { Input } from '@chakra-ui/react';

const [shareInputValue, setShareInputValue] = useState(0);

                        <Input
                            type="number"
                            textAlign={'center'}
                            borderRadius={0}
                            border="1px solid #E2E8F0;"
                            value={shareInputValue}
                            onChange={e => {
                                const enterValue = e.target.value;
                                console.log('enterValue', enterValue);
                                const removeZeroStartValue = enterValue.replace(/^0+/, '');
                                console.log('removeZeroStartValue', removeZeroStartValue);
                                setShareInputValue(Number(removeZeroStartValue));
                            }}
                        />

When I type 1 the Input will show 01 and continue to type 1 the Input will show 011

I think it should become 1 and 11 ?

![enter image description here

enter image description here

I try to use removeZeroStartValue and then setState, but it's not working

How to fix the issue ?

enter image description here


Solution

  • You're directly setting the value to 0 in your default state. Set it to null and add a placeholder instead.

    const [shareInputValue, setShareInputValue] = useState(null);
    
    
      
    
      <Input
          type="number"
          textAlign={"center"}
          borderRadius={0}
          border="1px solid #E2E8F0;"
          placeholder="0"
          value={shareInputValue}
          onChange={(e) => {
            setShareInputValue(e.target.value);
          }}
        />