Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use pure flatpickr in react?

I'm new in reactJS, and I am trying to use pure flatpickr (https://flatpickr.js.org , NOT react-flatpickr) Below is my current code. Any help on how to implement it properly?


import React, { Component } from "react"
import flatpickr from "flatpickr"

export default class Datepicker extends Component<IProps> {

  public render() {
    flatpickr(".datepicker")
    return (
        <div>
           <input type="text" className="datepicker" />
        </div>
    )
  }
}
like image 914
Yerlan Yeszhanov Avatar asked Dec 19 '18 09:12

Yerlan Yeszhanov


People also ask

How do you make a pure component in React?

A React component is considered pure if it renders the same output for the same state and props. For this type of class component, React provides the PureComponent base class. Class components that extend the React. PureComponent class are treated as pure components.

How do you use pure components?

ReactJS Pure Component Class compares current state and props with new props and states to decide whether the React component should re-render itself or Not. In simple words, If the previous value of state or props and the new value of state or props is the same, the component will not re-render itself.

What is pure and impure component in React?

A Pure function is a function that does not modify any external variable. And the Impure function modifies the external variable. A basic principle of functional programming is that it avoids changing the application state and variables outside its scope. Let see how it works in React.


1 Answers

flatpickr requires a node or selector passed into it. In React, for referring to the DOM, we use a ref

For handling events and providing other options, you can use the second argument for options.

Here is a demo:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.datePicker = React.createRef();
  }
  onChange(selectedDates, dateStr, instance) {
    console.log(selectedDates);
  }
  componentDidMount() {
    flatpickr(this.datePicker.current, {
      onChange: this.onChange
    });
  }
  render() {
    return(
      <input type="date" ref={this.datePicker} />
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>


<div id="root"></div>
like image 91
Agney Avatar answered Oct 12 '22 21:10

Agney