Why is 'emailjs' is not defined no-undef? - reactjs

I am following the Emailjs tutorial found here - https://www.emailjs.com/docs/tutorial/creating-contact-form/.
I am getting these error lines when the web page fails to compile:
Failed to compile./src/components/SwatForm.js
Line 42:29: 'emailjs' is not defined no-undef
Line 52:33: 'emailjs' is not defined no-undef
Line 64:33: 'emailjs' is not defined no-undef
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.
Here is the actual code from the tutorial in my react application.
import React, { Component } from 'react';
import { Container, Row, Col, Button, NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import groupPicture from "../church2019.jpg";
import Image from 'react-bootstrap/Image';
import './Site.css';
export class SwatForm extends Component {
static displayName = SwatForm.name;
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
feedback: "",
};
}
handleInputChange(event) {
event.preventDefault();
const target = event.target;
const name = target.name;
const value = target.value;
this.setState({ [name]: value });
}
render() {
return (
<Container>
<html>
<head>
<title>Contact Form</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
<script type="text/javascript">
(function() {
// https://dashboard.emailjs.com/admin/integration
emailjs.init('user_0rJrw0xxhrNqhld3WUc3q')
})();
</script>
<script type="text/javascript">
window.onload = function() {
document.getElementById('contact-form').addEventListener('submit', function (event) {
event.preventDefault();
// generate a five digit number for the contact_number variable
this.contact_number.value = Math.random() * 100000 | 0;
// these IDs from the previous steps
emailjs.sendForm('contact_service', 'contact_form', this)
.then(function () {
console.log('SUCCESS!');
}, function (error) {
console.log('FAILED...', error);
});
})
}
</script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
<script type="text/javascript">
(function() {
emailjs.init("user_0rJrw0xxhrNqhld3WUc3q")
})();
</script>
</head>
<form id="contact-form">
<input type="hidden" name="contact_number" />
<label>Name</label>
<input type="text" name="user_name" />
<label>Email</label>
<input type="email" name="user_email" />
<label>Message</label>
<textarea name="message"></textarea>
<input type="submit" value="Send" />
</form>
</html>
</Container>
);
}
}

There is a package for the use of this library. I think you should use it.
https://www.npmjs.com/package/emailjs-com
https://www.emailjs.com/docs/examples/reactjs/

Related

ReactJS - Uncaught RangeError: Maximum call stack size exceeded

I am trying to make a contact-manager-app from a YouTube video:
https://www.youtube.com/watch?v=0riHps91AzE&lc=Ugybk5M3ofjHsO8uHjd4AaABAg.9WHwkOL6qXV9WJu89p6VTV
Every time, I enter the inputs and click Add, the following error pops-up:
the screen-shot of the main page
I also get "6 moderate severity vulnerabilities" while downloading uuidv4. ( Put just in case, if it might help )
Also got "Module not found: Error: Can't resolve 'util' in 'C:\Users\loki\OneDrive\Desktop\ReactJS-YouTube\contact-app\node_modules\uuidv4\build\lib"
Here are all my files:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" integrity="sha512-8bHTC73gkZ7rZ7vpqUQThUDhqcNFyYi2xgDgPDHc+GXVGHXq+xPjynxIopALmOPqzo9JZj0k6OqqewdGO3EsrQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
App.js
import React, { useState, useEffect } from "react";
import { uuid } from "uuidv4";
import "./App.css";
import Header from "./Header";
import AddContact from "./AddContact";
import ContactList from "./ContactList";
function App() {
const LOCAL_STORAGE_KEY = "contacts";
const [contacts, setContacts] = useState([]);
const addContactHandler = (contact) => {
console.log(contact);
setContacts([...contacts, { id: uuid(), ...contact }]);
};
const removeContactHandler = (id) => {
const newContactList = contacts.filter((contact) => {
return contact.id !== id;
});
setContacts(newContactList);
};
useEffect(() => {
const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (retriveContacts) setContacts(retriveContacts);
}, []);
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);
return (
<div className="ui container">
<Header />
<AddContact addContactHandler={addContactHandler} />
<ContactList contacts={contacts} getContactId={removeContactHandler} />
</div>
);
}
export default App;
ContactList.js
import React from "react";
import ContactCard from "./ContactCard";
const ContactList = (props) => {
console.log(props);
const deleteContactHandler = (id) => {
props.getContactId(id);
};
const renderContactList = props.contacts.map((contact) => {
return(
<ContactCard contact={contact} clickHandler = { deleteContactHandler } key = { contact.id}/>
);
})
return(
<div className="ui celled list">
{renderContactList}
</div>
);
}
export default ContactList;
ContactCard.js
import React from "react";
import user from "../images/user.jpg";
const CardContact = (props) => {
const {id, name, email} = props.contact;
return(
<div className="item">
<img className="ui avatar image" src={user} alt="user" />
<div className="content">
<div className="header">{name}</div>
<div>{email}</div>
</div>
<i className="trash alternate outline icon"
style={{color:"red",marginTop:"7px"}}
onClick={() => props.clickHandler(id)}>
</i>
</div>
);
};
export default CardContact;
AddContact.js
import React from "react";
class AddContact extends React.Component {
state = {
name: "",
email: "",
};
add = (e) => {
e.preventDefault();
if (this.state.name === "" || this.state.email === "") {
alert("ALl the fields are mandatory!");
return;
}
this.props.addContactHandler(this.state);
this.setState({ name: "", email: "" });
};
render() {
return (
<div className="ui main">
<h2>Add Contact</h2>
<form className="ui form" onSubmit={this.add}>
<div className="field">
<label>Name</label>
<input
type="text"
name="name"
placeholder="Name"
value={this.state.name}
onChange={(e) => this.setState({ name: e.target.value })}
/>
</div>
<div className="field">
<label>Email</label>
<input
type="text"
name="email"
placeholder="Email"
value={this.state.email}
onChange={(e) => this.setState({ email: e.target.value })}
/>
</div>
<button className="ui button blue">Add</button>
</form>
</div>
);
}
}
export default AddContact;
From the uuidv4 npm page:
Most of the functionality of uuidv4 module is already included in uuid since version 8.3.0, so most of the functions of uuidv4 module have already been marked as deprecated.
So, importing uuidv4 module in your App.js is causing this error.
You can upgrade to the latest version of uuid library to get rid of this error.
Run these commands in the terminal in your project directory.
npm uninstall uuidv4
npm install uuid
And now, in App.js import uuid module instead of uuidv4
import { v4 as uuid } from 'uuid';
And now, you can use uuid() function to create UUIDs
To check more about uuid, you can see there documentation: https://github.com/uuidjs/uuid#quickstart
In your App.js:
On each useEffect (page renders) you are calling setContract , on useEffect below you are watching that contract as dependency , so it's rendering when contract is changing
useEffect(() => {
const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (retriveContacts) setContacts(retriveContacts);
}, []);
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);

React component not getting default state

Trying to learn React/RoR and in this simple test app I have a 'searchapp' react app. That sets a default for the language radioboxes.
import React from 'react'
import ReactDOM from 'react-dom'
import axios from "axios";
import SearchForm from "./searchForm";
class SearchApp extends React.Component {
constructor(props) {
super(props);
this.state = {
searchStrings: [],
subjectName: "",
language: 'English',
region: ""
};
this.getSearchStrings = this.getSearchStrings.bind(this);
}
componentDidMount() {
this.getSearchStrings();
}
handleClickLang = changeEvent => {
this.setState({
language: changeEvent.target.value
});
};
getSearchStrings() {
axios
.get("/api/v1/search_strings")
.then(response => {
const searchStrings = response.data;
this.setState({searchStrings});
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<>
<SearchForm />
</>
);
}
}
and then in the searchForm component I use that state to set and switch between two radio buttons.
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.subjRef = React.createRef();
//this.handleClickLang = this.handleClickLang.bind(this);
}
componentDidMount() {
this.setState({
language: 'English'
});
}
handleSubmit(e) {
e.preventDefault();
window.alert("sometext");
}
render() {
return (
<form onSubmit={this.handleSubmit} className="my-3">
<div className="form-row">
<div className="form-group col-md-8">
<p>Choose language</p>
</div>
<div className="form-row">
<div className="form-check">
<label>
<input
type="radio"
name="react-tips"
value="English"
checked={this.state.language === 'English'}
onChange={this.handleClickLang}
className="form-check-input"
/>
English
</label>
</div>
<div className="form-check">
<label>
<input
type="radio"
name="react-tips"
value="Russian"
checked={this.state.language === 'Russian'}
onChange={this.handleClickLang}
className="form-check-input"
/>
Russian
</label>
</div>
However when I run this I get the following error:
Uncaught TypeError: Cannot read properties of null (reading 'language')
I thought this was erroring because it cannot find a default language, however I initialised language to 'English' in the constructor for the SearchApp.
Is this me not understanding React state enough? Any help much appreciated.
In the componentDidMount i feel the language is getting to null, you can try the following:
Trying to learn React/RoR and in this simple test app I have a 'searchapp' react app. That sets a default for the language radioboxes.
import React from 'react'
import ReactDOM from 'react-dom'
import axios from "axios";
import SearchForm from "./searchForm";
class SearchApp extends React.Component {
constructor(props) {
super(props);
this.state = {
searchStrings: [],
subjectName: "",
language: 'English',
region: ""
};
this.getSearchStrings = this.getSearchStrings.bind(this);
}
componentDidMount() {
this.getSearchStrings();
}
handleClickLang = changeEvent => {
this.setState({
language: changeEvent.target.value
});
};
getSearchStrings() {
axios
.get("/api/v1/search_strings")
.then(response => {
const searchStrings = response.data;
this.setState({searchStrings,language: 'English'});
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<>
<SearchForm language={this.state.language}/>
</>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
And in the SearchForm component pass the language via props
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.subjRef = React.createRef();
//this.handleClickLang = this.handleClickLang.bind(this);
}
handleSubmit(e) {
e.preventDefault();
window.alert("sometext");
}
render() {
return (
<form onSubmit={this.handleSubmit} className="my-3">
<div className="form-row">
<div className="form-group col-md-8">
<p>Choose language</p>
</div>
<div className="form-row">
<div className="form-check">
<label>
<input
type="radio"
name="react-tips"
value="English"
checked={this.props.language === 'English'}
onChange={this.handleClickLang}
className="form-check-input"
/>
English
</label>
</div>
<div className="form-check">
<label>
<input
type="radio"
name="react-tips"
value="Russian"
checked={this.props.language === 'Russian'}
onChange={this.handleClickLang}
className="form-check-input"
/>
Russian
</label>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
But there are several more things:
Why are you also having language state in searchForm, you can have it in Search component and pass it via props
Yo are not initializing any state in the constructor in your SearchForm component
Adding a followup here for future reference.
As suggested by #Thor84no the problem was not adding state = {} to intialise state in the sub component.

Can return directly a component from a handling event function in Reactjs?

I have a form to add a category. I expect that when clicking on the add button, there is a notification showing in the corner screen if the input is empty. My idea is returning a Çomponent( or function) contains a toast in handleAddNewCategory() but it's not showing. I know that the library react-bootstrap can do showing toast like this
handleAddNewCategory(){
if(condition)
return toastr.info("message",...);
}
but I don't want to use it for now. Can anyone give me a solution to solve this with using only bootstrap. I'm totally new to Reactjs.
This is some minimal file:
import React, { Component } from "react";
import AddNewCategory from "./AddNewCategory";
import Notification from "./Notification";
class CategoryList extends Component {
constructor(props) {
super(props);
this.state = {
categoryNameInput: "",
categoryDescriptionInput: "",
};
}
...
handleAddNewCategory = () => {
const { categoryNameInput, categoryDescriptionInput } = this.state;
if (categoryNameInput.trim() === "") {
return <Notification message="Please enter category name" />;
}
if (categoryDescriptionInput.trim() === "") {
return <Notification message="Please enter category description" />;
}
};
render() {
return (
<div className="container">
...
<AddNewCategory handleAddNewCategory={this.handleAddNewCategory} />
...
</div>
);
}
}
export default CategoryList;
Notification component
import React, { Component } from "react";
class Notification extends Component {
render() {
const myStyle = {
zIndex: "1001",
position: "absolute",
top: "10px",
right: "10px",
};
return (
<div className="toast col-2" style={myStyle} data-autohide="false">
<div className="toast-header">
<strong className="mr-auto text-primary">Notice</strong>
</div>
<div className="toast-body">{this.props.message}</div>
</div>
);
}
}
export default Notification;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('.toast').toast('show');
});
</script>
</body>
</html>
don't use jquery to show the toast it's not the best practice and instead of conditionally rendering the component what you can do is. just render it ones and then controlled its visibility.
follow the below code:-
Notification component
import React, { Component } from "react";
class Notification extends Component {
render() {
const myStyle = {
zIndex: "1001",
position: "absolute",
top: "10px",
right: "10px",
};
return (
<div hidden={this.props.showToast} className="toast col-2" style={myStyle} data-autohide="false">
<div className="toast-header">
<strong className="mr-auto text-primary">Notice</strong>
</div>
<div className="toast-body">{this.props.message}</div>
</div>
);
}
}
export default Notification;
Notification component usage :-
class CategoryList extends Component {
constructor(props) {
super(props);
this.state = {
categoryNameInput: "",
categoryDescriptionInput: "",
toastMessage:'',
showToast:false
};
}
...
handleAddNewCategory = () => {
const { categoryNameInput, categoryDescriptionInput } = this.state;
if (categoryNameInput.trim() === "") {
this.setState({
toastMessage:'Please enter category name',
showToast:true
})
}
if (categoryDescriptionInput.trim() === "") {
this.setState({
toastMessage:'Please enter category name',
showToast:true
})
}
};
render() {
return (
<div className="container">
<Notification message={this.state.toastMessage} showToast={this.state.showToast}/>;
...
<AddNewCategory handleAddNewCategory={this.handleAddNewCategory} />
...
</div>
);
}
}
export default CategoryList;
here what i do is i initialise the boolean in state and enable it so that toast will be visible and i pass it directly throw props so that whenever your message and boolean changes it automatically reflects in your notification controller.
and to remove the toast just set {showToast} to false whenever you want. and remove the jquery part from your code

How to integrate bootstrap 4 datatable in reactjs?

i am working on reactjs in which i want to use bootstrap 4 data table. (Link: https://datatables.net/examples/styling/bootstrap4). i have imported the required js and css into the application but bootstrap 4 datatable pagination is not working as expectation. Following are the code and screenshort of the output:
enter image description here
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>Hailo Web Portal</title>
<!-- Favicon icon -->
<link rel="icon" href="assets/images/favicon.ico" type="image/x-icon">
<!-- fontawesome icon -->
<link rel="stylesheet" href="assets/fonts/fontawesome/css/fontawesome-all.min.css">
<!-- animation css -->
<link rel="stylesheet" href="assets/plugins/animation/css/animate.min.css">
<!-- vendor css -->
<link rel="stylesheet" href="assets/css/style.css">
<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" > -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
</head>
<body>
<div id = "app"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script src="assets/js/vendor-all.min.js"></script>
<!-- <script src="./assets/js/vendor-all.min.js"></script> -->
<script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/pcoded.min.js"></script>
<script src = 'index_bundle.js'></script>
<script>
$(document).ready(function() {
$('#example').DataTable();
});
</script>
</body>
</html>
main.js
/*import $ from 'jquery';
import Popper from 'popper.js'; */
/*
import '../node_modules/bootstrap/dist/js/bootstrap.bundle.min'; */
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App.js';
import 'bootstrap';
require('bootstrap/dist/css/bootstrap.css');
ReactDOM.render(<BrowserRouter><App /></BrowserRouter>,document.getElementById('app'));
login.js
import React, { Component } from "react";
import { Link } from "react-router-dom";
import "./Login.css";
import BackgroundImage from "../assets/backgroundImage.png";
/* const emailRegex = RegExp(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/); */
const emailRegex = RegExp(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
const formValid = ({ formErrors, ...rest }) => {
console.log("formErrors=====>", formErrors);
console.log("...rest========>", rest);
let valid = true;
Object.values(formErrors).forEach(val => {
console.log("val--->", val);
val.length > 0 && (valid = false);
});
Object.values(rest).forEach(val => {
val === null && (valid = false);
});
console.log("valid---->", valid);
return valid;
};
const bgimage = {
backgroundImage: `url(${BackgroundImage})`
};
class Login extends Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
email: null,
password: null,
formErrors: {
email: "",
password: ""
},
userLists: []
};
this.getAllUsersLists = this.getAllUsersLists.bind(this);
}
componentDidMount() {
this._isMounted = true;
this.getAllUsersLists();
}
componentWillUnmount() {
this._isMounted = false;
}
getAllUsersLists = () => {
const url = "http://192.168.15.149" + ":9001" + "/getAllRoles";
const options = {
method: "GET"
};
fetch(url, options)
.then(results => results.json())
.then(
data => {
if (data.status == "Failure") {
if (this._isMounted) {
this.setState({ userLists: [] });
}
} else {
if (this._isMounted) {
this.setState({
userLists: data
});
}
}
},
error => {
if (this._isMounted) {
this.setState({ userLists: [] });
}
}
);
};
render() {
const { formErrors } = this.state;
return (
<div>
<h1>Test</h1>
<table id="example" className="table table-striped table-bordered" style={{ width: "100%" }}>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{this.state.userLists.map((ul, index) => (
<tr key={ul.id} id={index+1}>
<td>{ul.role_name}</td>
<td>{ul.description}</td>
<td>{ul.status}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default Login;
Any help is appreciated. Thanks in advance.
I would suggest you to use react-bootstrap-table-next
you can try demo and follow the docs for more functionallity and much more easy to customised for the react you can try
try it:
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();
});
}
this work for me.

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>
)
}
}
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>
Example with hooks & Typescript (I had to use useCallback and useRef to make it work):
// Or configure the styling elsewhere.
import 'flatpickr/dist/flatpickr.css';
import flatpickr from 'flatpickr';
import { Instance } from 'flatpickr/dist/types/instance';
export default function Comp() {
const fp1 = useRef() as MutableRefObject<Instance>;
const inputRef = useCallback((node) => {
if (node !== null) {
fp1.current = flatpickr(node, {});
}
}, []);
return (<input type="date" ref={inputRef} />);
}

Resources