Search code examples
reactjsreact-nativereduxreact-reduxreact-dates

React-Dates in component using Redux


As a newbie in React and Redux, i'm trying to use react-dates in a component.

This is my code:

import * as React from 'react';
import { connect } from 'react-redux';
import { ApplicationState } from '../store';
import * as DateState from '../store/Date';
import * as SingleDatePicker from 'react-dates';

type DateProps = DateState.DateState & typeof DateState.actionCreators;

class DatePickerSingle extends React.Component<DateProps, any> {

    public render() {

        let { date } = this.props;
        return (
            <div>
                <SingleDatePicker
                    id="date_input"
                    date={this.props.date}
                    focused={this.state.focused}
                    onDateChange={(date) => { this.props.user({ date }); }}
                    onFocusChange={({ focused }) => { this.setState({ focused }); }}
                    isOutsideRange={() => false}
                    displayFormat="dddd LL">
                </SingleDatePicker>
            </div>
        );
    }
}

export default connect(
    (state: ApplicationState) => state.date, 
    DateState.actionCreators                 
)(DatePickerSingle);

This returns the following error:

Exception: Call to Node module failed with error: TypeError: Cannot read property 'focused' of null

focused an onFocusChange should receive the "datepicker state" as far as I understand.

Docs:

onFocusChange is the callback necessary to update the focus state in the parent component. It expects a single argument of the form { focused: PropTypes.bool }.

I think the problem is that I inject the DateState in the DatePickerSingle component, which doesn't know about focused state.

Is it possible to use my "own" state and the state from the DatePicker together? Or what is the best approach?

I'm trying for quite a while now, and I hope someone can help me with this.

UPDATE

enter image description here


Solution

  • The answer is quite simple: this.state is null because it has not been initialized. Just add

    constructor() {
      super();
      this.state = {
        focused: false
      }
    }
    

    Anything coming from redux will be passed to your component as props, you can have component state in addition to that.