how to use pure flatpickr in react? - reactjs

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} />);
}

Related

Is there a way of passing props to class component?

I'm a beginner in React.
I still quite don't understand how to pass props to a class component like we do in a function.
Example of a function:
const SurveyFormReview = ({ onCancel, formValues, submitSurvey, history }) => {
return (
...
<button
onClick={() => submitSurvey(formValues, history)}
className="green btn-flat right white-text"
>
...
);
};
Example of a class Component:
class ImageUpload extends Component {
render() {
return (
// I want to use props in here
)
}
}
For example
<ImageUpload propExample="property" />
Inside ImageUpload component you can access it by writing:
this.props.propExample
Just use whatever attributes you want when using the ImageUpload component:
<ImageUpload propA="someValue" propB={someVariable}/>
From the ImageUpload component, just call the props property:
someFunction = () => {
var propAValue = this.props.propA;
var propBValue = this.props.propB;
}
That's it!
You can pass any value as a props in Class and functional components in react. Read more about props
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
};
ReactDOM.render(
<Welcome name="Sara" />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

React portal is not showing on top

i am facing issue with using react create portal.
the modal component is not shown on top of parent.
i have two roots in index.html, one is "Modal" and another is "root".
created portal on in Modal is not shown on top of the "root" tree.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel="stylesheet" type="text/css" href="./style.css" />
</head>
<body>
<div id="modal"></div>
<div id="root"></div>
<script src="App.js"></script>
</body>
</html>
App.js:
import React from "react"
import ReactDOM from "react-dom"
import Modal from "./Modal"
class App extends React.Component
{
constructor(){
super();
this.inputNode = React.createRef();
this.submitHandler = this.submitHandler.bind(this)
}
submitHandler(){
console.log("onclided")
this.inputNode.current.focus();
event.preventDefault();
}
render(){
return(
<div>
<span
onClick={this.submitHandler}>Name</span>
<input
ref={this.inputNode}
>
</input>
<Modal/>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById("root"))
Modal.js:
import React from "react"
import ReactDOM from "react-dom"
const modalRoot = document.getElementById('modal');
class Modal extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
}
componentDidMount() {
modalRoot.appendChild(this.el);
}
componentWillUnmount() {
modalRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(
<div>hello modal</div>,
this.el,
);
}
}
export default Modal;
can someone tell me what i am doing wrong here ?
in your app.js
import React from "react"
import ReactDOM from "react-dom"
import Modal from "./Modal"
const mainContainer = document.getElementById('root');
const portalContainer = document.getElementById('modal');
class App extends React.Component
{
constructor(){
super();
this.inputNode = React.createRef();
this.submitHandler = this.submitHandler.bind(this);
this.el = document.createElement('div');
}
componentDidMount() {
portalContainer.appendChild(this.el);
}
componentWillUnmount() {
portalContainer.removeChild(this.el);
}
submitHandler(){
console.log("onclided")
this.inputNode.current.focus();
event.preventDefault();
}
render(){
return(
<div>
<span
onClick={this.submitHandler}>Name</span>
<input
ref={this.inputNode}
>
</input>
{ReactDOM.createPortal(
<Modal />,
portalContainer,
);}
</div>
)
}
}
ReactDOM.render(<App/>, mainContainer)
in your Modal.js
import React from "react"
import ReactDOM from "react-dom"
class Modal extends React.Component {
render() {
<div>hello modal</div>
}
}
export default Modal;
I found the out the issue. i didn't provide style position to "Modal" div as : fixed/absolute ,so by default it took static. and both "root" and "modal" are shown up and down.
nothing wrong with my code.

React JSX Syntax

I am using the code below to create a react component.
function Button(props) {
return (
<button onClick={props.handleClick}>
{props.name}
</button>
)
}
class LikeButton extends React.Component {
handleClick = () => {
console.log('ciao');
}
render() {
return (
<Button handleClick={this.handleClick}
name='Get' />
)
}
}
ReactDOM.render(<LikeButton />, document.getElementById('buttons'));
I tried the code with sandbox and it works perfectly. The problem is when I run my code, I get an error syntax in the third line of my Button function.
At first, I thought it was an error related to babel but I am using the CDN and it is supposed to work.
If you are using Babel from a CDN for experimentation you need to make sure your script tag has the attribute type="text/babel" as well.
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="buttons"></div>
<script type="text/babel">
function Button(props) {
return <button onClick={props.handleClick}>{props.name}</button>;
}
class LikeButton extends React.Component {
handleClick = () => {
console.log('ciao');
}
render() {
return <Button handleClick={this.handleClick} name='Get' />;
}
}
ReactDOM.render(<LikeButton />, document.getElementById('buttons'));
</script>

How to pass ref by props in ReactJs?

This is my components logic:
component_1
|
'------component_2
I have an input in component_2, and I want to put .focus () on it, but the function that will do this is in component_1, how can I do it?
And I think it will do the ref, if I'm wrong please correct me.
Since React 16.3, you can use React.createRef() in Component1 and pass it to the input via Component2 using ref forwarding:
const Component2 = React.forwardRef((props, ref) => (
<input ref={ref} />
));
class Component1 extends React.Component {
ref = React.createRef();
componentDidMount() {
setTimeout(() => this.ref.current.focus(), 1000);
}
render() {
return <Component2 ref={this.ref} />;
}
}
ReactDOM.render(
<Component1 />,
document.getElementById('demo')
);
<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>
<div id="demo"></div>

Cannot read property 'value' of null?

I am getting error when I try to use this.username.value. I want to get value of textbox to show in label. I am newbie to react. How to get value from Textbox to a variable and display in Label using InputRef.
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { createStructuredSelector } from 'reselect';
import TextBox from 'components/Atoms/TextBox';
import makeSelectTestPage from './selectors';
export class TestPage extends React.PureComponent {
constructor(props) {
super(props);
this.username ='',
this.handelChange = this.handelChange.bind(this);
}
handelChange() {
console.log("Log",this.username.value);
<label> this.username.value</label>
}
render() {
return (
<div>
<Helmet
title="TestPage"
meta={[
{ name: 'description', content: 'Description of TestPage' },
]}
/>
<TextBox labelName="Input Vaue" placeholder="Test" ref={(inputRef) => { this.username = inputRef; }} defaultValue="Text" ></TextBox>
<button onClick={this.handelChange}>Login</button>
</div>
);
}
}
TestPage.propTypes = {
dispatch: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
TestPage: makeSelectTestPage(),
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(TestPage);
In your question there are a few mistakes. Try to understand the next code and your will be able to apply it to your example :
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
value: "",
username: ""
}
}
handleChange(e){
this.setState({value: e.target.value})
}
handleClick(){
this.setState({username: this.state.value})
}
render(){
return (
<div>
<label>{this.state.username}</label><br />
<input value={this.state.value} onChange={this.handleChange.bind(this)}></input><br />
<button onClick={this.handleClick.bind(this)}>Login</button>
</div>
)
}
}
ReactDOM.render(<Test />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container'/>
Here is the fiddle.

Resources