Reset value of RangePicker Ant design - reactjs

I'm using RangePicker from ant design in my app. I'va faced with following issue: when to click on button "reset" I can't clear the value in RangePicker component. Please help me how to do it? I've tried assign defaultValue but It doesn't work.

Use the value parameter of RangePicker instead.
Something like this should probably work. Wasnt in a position to make a enviroment and test it but hopefully you get the idea. Ask any questions if theres something that is not clear.
const SomeComponent = props => {
const [fromDate, setFromDate] = useState('2000-01-01');
const [toDate, setToDate] = useState('2000-01-02');
const onChangeDateRange = (dates, datesString) => {
setFromDate(datesString[0]);
setFromDate(datesString[1]);
//More code
}
const onResetClick = () => {
setFromDate('2000-01-01');
setToDate('2000-01-02');
}
return (
<>
<RangePicker
onChange={onChangeDateRange}
value={[moment(fromDate, dateFormat), moment(toDate, dateFormat)]}
/>
<Button onClick={onResetClick}>Reset</Button
</>
)
}
The docs on ant design are very good and at the end you can find all availible parameters a component can have. DatePicker e.g. has a allowClear. https://ant.design/components/date-picker/

Related

Hello, on ReactJs, I loose focus on input when useState change value :

Here an example of the problem :
codesandbox.io
export default function App() {
const [hasInputChanged, setHasInputChanged] = useState(false);
let colorList = ["orange", "blue", "yellow"];
function handleChange(e) {
setHasInputChanged(true);
}
const MyLittleInput = () => {
return <input onChange={(e) => handleChange(e)} />;
};
return (
<>
{colorList.map((color) => (
<MyLittleInput key={color} />
))}
</>
);
}
I tried different solutions as defining Keys or using useRef but nothing worked
It's too much code to be debugged easily, but for what I can see on the fiddle, there are serveral things wrong, first of all you are doing really too much things for a simple increment/decrement of a input value. But most important you are defining theyr value using the parametresListe state, but never really changing it wit the setParametresListe function, which should be the only way to safely change controlled form inputs.
Just try to do a bit of cleaning on your code and to use the useState as it is meat to be used
Let us know any updates!
UPDATE:
Having a look at your cleaned code, the problem is that a input inside a component gets builded again and again.
The reason for that, is that each input should have they unique "key" prop, so react can easily understand what input is changed and update only that one.
You have 2 ways to make this work, for the first, I've edited your code:
import "./styles.css";
import React, { useState } from "react";
const DEFAULT_INPUT_STATE = {
orange: "",
blue: "",
yellow: ""
};
export default function App() {
let colorList = ["orange", "blue", "yellow"];
const [inputState, setInputState] = useState(DEFAULT_INPUT_STATE);
const handleChange = (e) => {
const { name, value } = e.target;
console.log(name);
setInputState({
...inputState,
[name]: value
});
};
return (
<>
{colorList.map((color, i) => (
<input
key={color}
name={color}
value={inputState[color]}
onChange={(e) => handleChange(e)}
/>
))}
</>
);
}
As you can see, I've just removed the component for the input and did a bit of other changes, but If you still want to use a component, you can moove all the .map function inside of it, but there's no way to create the input inside a component if it is in a .map function
There is too much code, difficult to follow through, in your example. In the nutshell, I see in dev tools, when I update an input, the entire example component is re-rendered, thus all input elements got destroyed and replaced by newly created ones, without focus. It must be just a bug in your code: once an input is updated it renders different stuff, instead of just changing the input value. But it is beyond something someone here would debug for you for free :D

Proper way to change calendar date clear icon in DatePicker for AntD

I want to change the clear icon of a date picker from the ant design framework.
Is it possible ?
Reason - I want to reset the date to today when it clicks. So close-icon is not appropriate.
Since antd uses rc-picker to create DatePicker component, you can use clearIcon attribute to customize clear icon, but since you need to reset datePicker's value to today with click on clear, you need to do a bit more to handle this requirement, here is an example:
function PickerWithCustomClear() {
const [date, setDate] = React.useState(null);
const [shoudlReset, setShouldReset] = React.useState(false);
const onChange = (date) => {
setDate(date);
if (!date && shoudlReset) {
setDate(moment());
setShouldReset(false);
}
};
return (
<DatePicker
onChange={onChange}
allowClear={true}
value={date}
clearIcon={
// you can use every element here
<SyncOutlined onMouseDown={(e) => setShouldReset(true)} />
}
/>
);
}
I've implemented an example you can find it Here.

React state showing differing values from each dynamically generated input field component

I've been banging my head against my keyboard for the past 8 hours trying to figure out why each input field is showing different values for the same state.
Here is the code -
const BeaconSettingsCard = (props) => {
const [settingsItems, setSettingsItems] = useState([]);
const handleAddBeaconBtnOnClick = () => {
const id = settingsItems.length;
const newItem = (
<InputItem
id={id}
key={id}
type="InputField"
title="Test Title"
value="Test Value"
onChange={(e) => handleBeaconIdInputFieldOnChange(e, id)}
/>
);
setSettingsItems((settingsItems) => [...settingsItems, newItem]);
};
const handleBeaconIdInputFieldOnChange = (e, id) => {
console.log("settingsItems: ", settingsItems); // each input field shows a different settingsItems value ??
};
let cardHeaderButton = (
<InputItem type="Button" width="150px" onClick={handleAddBeaconBtnOnClick}>
Click to Add
</InputItem>
);
return (
<SettingsCard
headerButton={cardHeaderButton}
settingsItems={settingsItems}
/>
);
};
export default BeaconSettingsCard;
When I log the "settingsItems" state in the onChange event for each input field, I get different values.
On the first dynamically generated inputfield, it logs settingsItems as []. On the second, it logs [{React Component}]. On the third, it logs [{React Component}, {React Component}] and so forth.
These should all be logging the same state value! My friend who is a react wiz couldn't seem to figure this out either. Really hoping someone here can. Thank you.
I solved this strange issue by converting the code from React hooks to a normal React component.
Not ideal, but works. Hopefully if someone runs into a strange issue like this, this solution will work for you too.

Field/Input label based on record in react admin

I'd like part of the record to be included in the label for a BooleanField (and BooleanInput). I'm trying to use WithProps to accomplish this.
If I use
<BooleanField source="FileSystem" label="FileSystem" />
This seems to work just fine. If, instead I try to wrap it
const makeLabel = (props)=>{
let label = `Filesystem for ${props.record.id}`;
return {label};
}
const withLabel = withProps(makeLabel);
const BooleanFieldWithLabel = compose(withLabel)((props)=>{
console.log("props after compose",props);
return <BooleanField {...props}/>
});
And then use <BooleanFieldWithLabel source="FileSystem" /> It doesn't render any label. I've tried a few different ways and nothing seems to work even though I can see in the console.log that the correct label is in props. What am I doing wrong here?
I have the same question, I cannot display the label base on field's value on "Show" page.
From react-admin source code, it seems only I set "addLabel" prop on the direct child of "SimpleShowLayout" or "TabbedShowLayout", then I can see label on my custom field.
But it is not configurable, I want to show/hide label base on field's value. Do I need to implement my own custom "SimpleShowLayout" or "TabbedShowLayout"? Or is there any better approaches?
Update my post.
I just figure out the solution by implementing an HOC like below. I am wondering is there any better approaches to implement the same feature?
import React from "react";
import get from "lodash/get";
import { TextField, DateField, Labeled } from "react-admin";
const NullableField = WrappedComponent => props => {
const { record, source } = props;
const value = get(record, source);
return value ? (
<Labeled {...props}>
<WrappedComponent {...props} />
</Labeled>
) : null;
};
const NullableTextField = NullableField(TextField);
const NullableDateField = NullableField(DateField);
export { NullableTextField, NullableDateField };

Wrapping Antd Component

I want to wrap antd component eg. Input into MyInput so I can add support for new pros and classNames, however it stoped working when I put then inside of the Form
MyInput.js
import { Input } from 'antd';
function MyInput({ className='', ...rest }) {
const computedClassName = 'my-input '+className;
return (
<Input className={computedClassName} {...rest} />
);
}
MyInput.defaultProps = Input.defaultProps;
MyInput.propTypes = Input.propTypes;
MyInput.Group = Input.Group;
MyInput.Search = Input.Search;
MyInput.TextArea = Input.TextArea;
Now if I put <MyInput /> inside of <Form/> it stops working
DEMO
I tried to debug, looks like the saveRef function in rc-form/lib/createBaseForm is receiving null as component argument, so this makes me feel is a ref problem, but I'm not sure how to fix it :S
Nevermind I found the answer...
As per Refs documentation
refs doesnt work on stateless components, change it to class and worked

Resources