I want to use https://github.com/t1m0n/air-datepicker with in a React app, but it doesn't work.
import React from 'react';
import AirDatepicker from 'air-datepicker';
class Datepicker extends React.Component {
render() {
return(
<AirDatepicker />
)
}
}
export default Datepicker;
`
<script src="./../bower_components/jquery/dist/jquery.min.js"></script>
This produces:
error($ is not defined)
Another approach:
import React from 'react';
import $ from 'jquery';
import AirDatepicker from 'air-datepicker';
class Datepicker extends React.Component {
render() {
return(
<AirDatepicker />
)
}
}
export default Datepicker;
Same error.
How can I integrate a jQuery plugin with React?
First of all
air-datepicker
is not React component, it's jQuery plugin, so it won't work like in your examples.Secondly, for proper work, jQuery should be availabel in global context, the most esiest ways to do this is to include it into page via
<script>
tag. It should be included before plugin script.To check if its really included and it available globally, just type in Chrome console
window.jQuery
and press Enter it should return something likefunction (a,b){...}
. If not, when you doing something wrong, checksrc
attribute of<script>
tag, maybe it pointing to wrong destinationHow to get it worked in React?
Well, the most simpliest way is just to initialize plugin on any DOM element in your component, like in regular JavaScript.
As separate component
Very simple datepicker React component example
Also don't forget to include css files.
air-datepicker
is not the React-component. It is the jquery-plugin, so we can follow this tutorial https://reactjs.org/docs/integrating-with-other-libraries.htmlBut it still not work cause the
jquery
not the dependency of theair-datepicker
.Follow the error message and the easiest way is to hake the
air-datepicker
. AddjQuery
as the dependency in the first line of theair-datepicker/dist/js/datepicker.js
Before:
After:
Thus
<AirDatepicker />
can works well as the React-component.