Reputation: 12309
I am having issue with my react component. In with i tried to bind my jquery DataTable. but every time i am getting error as
Uncaught TypeError: $(...).DataTable is not a function
Here is my implementation.
var test = React.createClass({
componentDidMount: function () {
var dataSet = [
[ '<div class="city-name">Arona Branch</div>', "Arona Street, Windhoek", '<div class="tel"> <span>Tel: 00 971 600 540000 </span> <span class="tel-or"> | </span> Fax: 00 971 4 222189</div>' ],
[ '<div class="city-name">Arona Branch</div>', "Arona Street, Windhoek", '<div class="tel"> <span>Tel: 00 971 600 540000 </span> <span class="tel-or"> | </span> Fax: 00 971 4 222189</div>' ],
[ '<div class="city-name">Arona Branch</div>', "Arona Street, Windhoek", '<div class="tel"> <span>Tel: 00 971 600 540000 </span> <span class="tel-or"> | </span> Fax: 00 971 4 222189</div>' ],
[ '<div class="city-name">Arona Branch</div>', "Arona Street, Windhoek", '<div class="tel"> <span>Tel: 00 971 600 540000 </span> <span class="tel-or"> | </span> Fax: 00 971 4 222189</div>' ],
]
$('#buy-example').DataTable( {
data: formattedResponse,
columns: [
{ title: "Name" },
{ title: "Address" },
{ title: "Office" },
{ title: "Start date" }
],
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": '<button class="btn show-map"><img class="map-icon" src="abcd/map-icon.PNG" /> Show in map</button>'
} ]
} );
})
},
render() {
return (
<div>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<div className="container">
<table id="buy-example" className="display" width="100%"></table>
<div id="no-search-data"> Test message </div>
</div>
)
}
})
Expert advice is most welcome!!
Upvotes: 0
Views: 4805
Reputation: 1
Try this.
npm install --save datatables.net-dt
In your root component you need import this dependences:
import "datatables.net-dt/js/dataTables.dataTables"
import "datatables.net-dt/css/jquery.dataTables.min.css"
so you can load your table.
componentDidMount() {
$(document).ready(function () {
$('#myTable').DataTable();
});
}
That worked for me.
Upvotes: 0
Reputation: 598
Since React starts running code before your div rendered to the page which includes script tags; probably, react can't find those scripts (jquery and datatables) so it gives error if you are working on local try to download those with npm and import them into your component file, if not try to put those script tags into bottom your html file's body tag instead of inside of react class.
Upvotes: 1