How to autofocus select input after async call? - javascript

I'm using Material UI's Autocomplete component, and I'm running into an issue. I have a debounced API call that is made when a user starts typing, and I disable the text input field while the call is being executed.
The issue is that disabling and then enabling the text field makes the text input lose focus. I've tried giving it an ID and grabbing it in the DOM and running .onFocus(), but that a) didn't work and b) isn't very React-y.
I also tried to add a useRef hook, but that didn't work either.
Any thoughts/suggestions?
Codesandbox

Hey you can add inputRef prop and then just wait until it is done loading. Here is exmaple:
const inputComponent = React.useRef(null);
return (
<Autocomplete
{/* ... */}
renderInput={params => (
<TextField
{/* ... */}
InputProps={{
{/* ... */}
inputRef: inputComponent,
{/* ... */}
}}
/>
)}
/>
);
And then I am guessing that you tried to focus element while it was still disabled, I guess a little race condition. You can add useEffect that is dependent on open and loading like this:
React.useEffect(() => {
if (!loading && open) {
inputComponent.current?.focus();
}
}, [loading, open]);
Here is the link to sandbox with it. Cheers, hope it helps.
P.S I don't think it is a good idea to disable the field while options are loading, it won't feel smooth for the user :)

Related

React Admin - How to disable validation onChange

I'm using react-admin, and I have a huge form, with a bunch of custom validation. It's very slow, even with the build version.
I tried to find a way to disable the validation on change and to have it only on blur or submit. But I have not found a solution or even workaround.
Every time a key is pressed in one of my input text (for example), the validation is triggered multiple times, and it takes a while for the letter to appear.
That's why I want to disable the validation on change.
Here's an example of one of my forms, every letter I write in one of my FormTab, the "validate me" is showing.
export const ThemeCreate: FC = (props: any) => (
<Create {...props} title="ui.themes.create" mutationMode="pessimistic">
<TabbedForm
toolbar={<GenericCreateToolbar />}
validateOnBlur
warnWhenUnsavedChanges
validate={() => {
console.log('validate me!');
}}
>
<MainFormTab />
<TranslationsFormTab />
</TabbedForm>
</Create>
);
You need to use the validateOnBlur={true} prop in the form component.
This prop is from final-form's <Form> component, see the last one in this doc page https://final-form.org/docs/react-final-form/types/FormProps

Material UI Slider component, update state on mouse release, while sliding in real time

I'm trying to find a way how to update the new state only on mouse release for a Material UI slider. While maintaining the ability to slide over the track and see the change in real-time.
Material UI provides 2 events: onChange and onChangeCommitted. The second provides the end result that I need, but the sliding trough the track is not visible in real-time, only at mouse release you see at what value you stopped.
Here is my component:
export default function RangeSlider() {
const classes = useStyles();
const [range, setRange] = React.useState([0, 37]);
const handleRange = (event, newValue) => {
setRange(newValue);
};
return (
<div className={classes.root}>
<Typography id="range-slider" gutterBottom>
Temperature range (onChangeCommitted event)
</Typography>
<Slider
value={range}
min={0}
max={50}
onChangeCommitted={handleRange}
valueLabelDisplay="auto"
getAriaValueText={valuetext}
/>
</div>
);
}
I want to find a way to have the ability to slide in real-time, and the state to be updated on mouse release. Is there an easy way to do this?
Please also check out this Sandbox, where I show you the 2 examples:
First is the sliding experience I need
Second is the way to update state
You have to combine your examples:
<Slider
value={value}
min={0}
max={50}
onChange={handleChange}
onChangeCommitted={handleRange}
valueLabelDisplay="auto"
getAriaValueText={valuetext}
/>
Why not just make a second state for committed change?
See sandbox
Edit: Code below.
Add state for range commit:
const [value2, setValue2] = React.useState([0, 37]);
On range commit handler (note: I am setting to the current state, unrelated to the mouse event this function gives me):
const setVal2 = () => setValue2(value);
Add range commit handler prop in addition to onChange:
onChange={handleChange}
onChangeCommitted={setVal2}
Display commited state:
<Typography id="range-slider" gutterBottom>
Temperature range (onChange event) - {value2[0]}:{value2[1]}
</Typography>
Use onUpdate!
onChange() triggers mouse release
onUpdate() triggers every change even when dragging...

Can't tap on checkboxes in React Native

I make tests on React Native. I use react-native-paper for this. This is my code:
{(!props.question.isSingleAnswer && props.question.answers.length) &&
<View>
{props.question.answers.map((item) => (
<List.Item
key={item.id.toString()}
title={item.title}
left={checkProps => <Checkbox {...checkProps} status='unchecked' onPress={() => addAnswer(props.question, item)}/>}
/>
))}
</View>
}
But I can't check checkboxes. The same problem with radio buttons.
Why does it happen and how can I fix it?
UPD: the problem was solved. Question is closed.
It is because you have the status of your checkbox to always unchecked, whereas you should always set status of your checkbox to anything dynamic for eg use a state.
I don't know what your addAnswer function does so have a look at this example for reference.

Logically disable Drag on react-native-draggable-flatlist

I'm trying to disable the drag feature based on some props change, not sure how to disable/enable it on 'react-native-draggable-flatlist', please find below the code
import DraggableFlatList from 'react-native-draggable-flatlist'
<DraggableFlatList
scrollPercent={5}
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item: any) => `draggable-item-${item}`}
onMoveEnd={({ data }: any) => {
this.setState({ data })
}}
/>
As per my requirement, I have totally disabled the parent component and it worked, but still not sure if there are any ways to disable it by passing a particular prop

React-final-form-array how to rerender form based on new state

I'm using react-final-form-arrays to build a dynamic field system, so far the scenario would be like this:
User clicks on button to open the editor modal (Add/Remove custom field using react-final-form-array. Once done, click Save and it will update the primary form.
The primary form is also using react-final-form-array to loop through the fields and render, without the Add/Remove button added.
I've tried to put a very sample from here: https://codesandbox.io/s/react-final-form-field-arrays-wbhgq?fontsize=14
In that sample, <Form1 /> is actually the editor form. Once submitted, <Form2 /> will render with new fields updated.
If I reload the page, it works but of course this is not what it should have been.
What should I change to make my <Form2 /> update ?
Thanks in advance
I'm not sure if I understood you correctly but the main idea is to create a store for the initialValues using useState or state of class component
const App = () => {
const [initialValues, setInitialValues] = useState();
return (
<Styles>
<Form1 onSubmit={setInitialValues} />
<Form2 initialValues={initialValues} />
</Styles>
);
};
If it is not what you want to achieve explain it in details

Categories

Resources