Reputation: 1923
In react, I am trying to add a search feature based on date selection. I have referred and using https://github.com/wojtekmaj/react-date-picker.
function Result(props) {
const [value, onChange] = useState(new Date());
return(
<div>
<DatePicker onChange={onChange} value={value} />
</div>
);
}
My other class component,
handleOnClick = (e) => {
console.log(e);
}
<Result handleOnclick={this.handleOnclick} />
Now I want to call my own function handleOnclick
as soon as date has been selected by passing the value(date).
In my custom function I should be able to fetch the selected date.
Dependencies are,
"react": "^17.0.1",
"react-date-picker": "^8.0.3",
"react-dom": "^17.0.1",
"react-scripts": "4.0.0",
"web-vitals": "^0.2.4"
How can I achieve this changes? Please help me.
Upvotes: 0
Views: 4299
Reputation: 16334
You can pass a custom function to the onChange prop and update the state from there. and carry out your custom logic there.
import React, { useState } from 'react';
import DatePicker from 'react-date-picker';
function Result(props) {
const [value, onChange] = useState(new Date());
const onDateChange=(newDate)=>{
//Your custom code here
props.handleOnclick(newDate);
onChange(newDate);
};
return (
<div>
<DatePicker
onChange={onDateChange}
value={value}
/>
</div>
);
}
The other option is to use the useEffect and add the value as a dependency which will run when the value is changed.
useEffect(()=>{
//your custom code here
},[value]);
Upvotes: 2