I need to add two buttons below the input field.
One button will allow saving the input in the textarea, and another aborting.
The buttons should be displayed when the input is focused.
Currently, the problem is that when I click any of the buttons, the input gets blurred again and thus they disappear and the onClick event doesn't happen.
I use MUI and Formik.
Can anyone tell me how to fix it?
const [buttonClicked, setButtonClicked] = useState(false);
...
return (
...
<Box sx={inspectionWrapperStyles} mb={'0.25rem'}>
<MultiLineInput
name={fieldName}
noMargin
required={required}
label={label}
onFocus={() => setInputFocused(true)}
onBlur={() => setInputFocused(false)}
ref={inputRef}
/>
{inputFocused && (
<>
<IconButton
altText=""
onClick={() => {
console.log('Saved');
}}
>
<SaveIcon />
</IconButton>
<IconButton
altText=""
onClick={() => {
console.log('Aborted');
}}
>
<XCircleIcon />
</IconButton>
</>
)}
</Box>
...
)
CodePudding user response:
Looks like currently as you click a button the focus of the input is lost, so they disappear. Maybe it's a good idea to check if the button is clicked and only then hide it, like this:
{inputFocused && !buttonClicked (
then in both button's onClick
you can add:
onClick={() => {
console.log('Aborted');
setButtonClicked(true);
}}
only thing left is to make sure that we reset it when input is focused again:
onFocus={() => {
setInputFocused(true);
setButtonClicked(false);
}}
CodePudding user response:
const [showButton, setShowButton] = useState(false); // add this
<MultiLineInput
name={fieldName}
noMargin
required={required}
label={label}
onFocus={() =>{
setInputFocused(true)
setShowButton(true) // add this
}}
onBlur={() => setInputFocused(false)}
ref={inputRef}
/>
{inputFocused && showButton && (
<>
<IconButton
altText=""
onClick={() => {
console.log('Saved');
setShowButton(false) // add this if you want to hide buttons
}}
>
<SaveIcon />
</IconButton>
<IconButton
altText=""
onClick={() => {
console.log('Aborted');
setShowButton(false) // add this if you want to hide buttons
}}
>
<XCircleIcon />
</IconButton>
</>
)}