How to Convert a Class Component to a Functional Component in React? - reactjs

I had never used React Class Components And Want to shoot confetti when some event happened. I'm confused with Class Component. Hope You can help with this issue. tried by creating arrow functions and removing this keyword .But I can't understand how to transform getInstance() function even why it is there?
import React, { Component } from 'react';
import ReactCanvasConfetti from 'react-canvas-confetti';
export default class Confetti extends Component {
getInstance = (instance) => {
// saving the instance to an internal property
this.confetti = instance;
}
onClickDefault = () => {
// starting the animation
this.confetti();
}
onClickCustom = () => {
// starting the animation with custom settings
this.confetti({ particleCount: Math.ceil(Math.random() * 1000), spread: 180 });
}
onClickCallback = () => {
// calling console.log after the animation ends
this.confetti().then(() => {
console.log('do something after animation');
});
}
onClickReset = () => {
// cleaning the canvas
this.confetti.reset();
}
render() {
const style = {
position: 'fixed',
width: '100%',
height: '100%',
zIndex: -1
};
const stylediv = {
position: 'fixed',
width: '100%',
height: '100%',
zIndex: 300000
};
return (
<>
<div style={stylediv}>
<ReactCanvasConfetti
// set the styles as for a usual react component
style={style}
// set the class name as for a usual react component
className={'yourClassName'}
// set the callback for getting instance. The callback will be called after initialization ReactCanvasConfetti component
refConfetti={this.getInstance}
/>
<button onClick={this.onClickDefault}>Fire with default</button>
<button onClick={this.onClickCustom}>Fire with custom</button>
<button onClick={this.onClickCallback}>Fire with callback</button>
<button onClick={this.onClickReset}>Reset</button>
</div>
</>
);
}
}
I'm trying to create Functional Component of the above Class Component

import React, { useRef } from 'react';
import ReactCanvasConfetti from 'react-canvas-confetti';
const Confetti = () => {
const Ref = useRef()
const getInstance = (instance) => {
if (Ref.current) {
Ref.current.confetti = instance
}
}
const onClickDefault = () => {
Ref.current.confetti();
}
const onClickCustom = () => {
Ref.current.confetti({ particleCount: Math.ceil(Math.random() * 1000),
spread: 180 });
}
const onClickCallback = () => {
Ref.current.confetti().then(() => {
console.log('do something after animation');
});
}
const onClickReset = () => {
Ref.current.confetti.reset();
}
const style = {
position: 'fixed',
width: '100%',
height: '100%',
zIndex: -1
};
const stylediv = {
position: 'fixed',
width: '100%',
height: '100%',
zIndex: 300000
};
return (
<>
<div ref={Ref} style={stylediv}>
<ReactCanvasConfetti
style={style}
className={'yourClassName'}
refConfetti={getInstance}
/>
<button onClick={onClickDefault}>Fire with default</button>
<button onClick={onClickCustom}>Fire with custom</button>
<button onClick={onClickCallback}>Fire with callback</button>
<button onClick={onClickReset}>Reset</button>
</div>
</>
);
}
export default Confetti

Related

How to convern ANTD class-based component to react function-based component

Can anyone give a suggestion on how can I convert Ant Design class-based component into function-based? I am new to class-based, so it is pretty confusing for me to convert class components. Now, my application is a functional-based component. Any suggestion will be appreciated!
Transfer Component
import { Transfer, Button } from 'antd';
class App extends React.Component {
state = {
mockData: [],
targetKeys: [],
};
componentDidMount() {
this.getMock();
}
getMock = () => {
const targetKeys = [];
const mockData = [];
for (let i = 0; i < 20; i++) {
const data = {
key: i.toString(),
title: `content${i + 1}`,
description: `description of content${i + 1}`,
chosen: Math.random() * 2 > 1,
};
if (data.chosen) {
targetKeys.push(data.key);
}
mockData.push(data);
}
this.setState({ mockData, targetKeys });
};
handleChange = targetKeys => {
this.setState({ targetKeys });
};
renderFooter = (props, { direction }) => {
if (direction === 'left') {
return (
<Button size="small" style={{ float: 'left', margin: 5 }} onClick={this.getMock}>
Left button reload
</Button>
);
}
return (
<Button size="small" style={{ float: 'right', margin: 5 }} onClick={this.getMock}>
Right button reload
</Button>
);
};
render() {
return (
<Transfer
dataSource={this.state.mockData}
showSearch
listStyle={{
width: 250,
height: 300,
}}
operations={['to right', 'to left']}
targetKeys={this.state.targetKeys}
onChange={this.handleChange}
render={item => `${item.title}-${item.description}`}
footer={this.renderFooter}
/>
);
}
}
ReactDOM.render(<App />, mountNode);
in function component to define state you can use useState hook, and also instead of lifecycles such as componentDidMount, componentDidUpdate, ... you can use useEffect hook, liek this:
import {useState, useEffect} from 'react';
import { Transfer, Button } from 'antd';
function App() {
const [state, setState] = useState({
mockData: [],
targetKeys: [],
});
const getMock = () => {
const targetKeys = [];
const mockData = [];
for (let i = 0; i < 20; i++) {
const data = {
key: i.toString(),
title: `content${i + 1}`,
description: `description of content${i + 1}`,
chosen: Math.random() * 2 > 1,
};
if (data.chosen) {
targetKeys.push(data.key);
}
mockData.push(data);
}
setState({ mockData, targetKeys });
};
useEffect(()=>{
getMock();
}, [])
const handleChange = targetKeys => {
setState(prevState => ({ ...prevState, targetKeys }));
};
const renderFooter = (props, { direction }) => {
if (direction === 'left') {
return (
<Button size="small" style={{ float: 'left', margin: 5 }} onClick={getMock}>
Left button reload
</Button>
);
}
return (
<Button size="small" style={{ float: 'right', margin: 5 }} onClick={getMock}>
Right button reload
</Button>
);
};
return (
<Transfer
dataSource={state.mockData}
showSearch
listStyle={{
width: 250,
height: 300,
}}
operations={['to right', 'to left']}
targetKeys={state.targetKeys}
onChange={handleChange}
render={item => `${item.title}-${item.description}`}
footer={renderFooter}
/>
);
}

setting ref on functional component

I am trying to change this class based react component to a functional component but i am gettig an infinite loop issue on setting the reference, i think its because of on each render the ref is a new object.
How could i convert the class based component to a functional component
index-class.js - Ref
class Collapse extends React.Component {
constructor(props) {
super(props);
this.state = {
showContent: false,
height: "0px",
myRef: null,
};
}
componentDidUpdate = (prevProps, prevState) => {
if (prevState.height === "auto" && this.state.height !== "auto") {
setTimeout(() => this.setState({ height: "0px" }), 1);
}
}
setInnerRef = (ref) => this.setState({ myRef: ref });
toggleOpenClose = () => this.setState({
showContent: !this.state.showContent,
height: this.state.myRef.scrollHeight,
});
updateAfterTransition = () => {
if (this.state.showContent) {
this.setState({ height: "auto" });
}
};
render() {
const { title, children } = this.props;
return (
<div>
<h2 onClick={() => this.toggleOpenClose()}>
Example
</h2>
<div
ref={this.setInnerRef}
onTransitionEnd={() => this.updateAfterTransition()}
style={{
height: this.state.height,
overflow: "hidden",
transition: "height 250ms linear 0s",
}}
>
{children}
</div>
</div>
);
}
}
what i have tried so far.
index-functional.js
import React, { useEffect, useState } from "react";
import { usePrevious } from "./usePrevious";
const Collapse = (props) => {
const { title, children } = props || {};
const [state, setState] = useState({
showContent: false,
height: "0px",
myRef: null
});
const previousHeight = usePrevious(state.height);
useEffect(() => {
if (previousHeight === "auto" && state.height !== "auto") {
setTimeout(
() => setState((prevState) => ({ ...prevState, height: "0px" })),
1
);
}
}, [previousHeight, state.height]);
const setInnerRef = (ref) =>
setState((prevState) => ({ ...prevState, myRef: ref }));
const toggleOpenClose = () =>
setState((prevState) => ({
...prevState,
showContent: !state.showContent,
height: state.myRef.scrollHeight
}));
const updateAfterTransition = () => {
if (state.showContent) {
this.setState((prevState) => ({ ...prevState, height: "auto" }));
}
};
return (
<div>
<h2 onClick={toggleOpenClose}>{title}</h2>
<div
ref={setInnerRef}
onTransitionEnd={updateAfterTransition}
style={{
height: state.height,
overflow: "hidden",
transition: "height 250ms linear 0s"
}}
>
{children}
</div>
</div>
);
};
usePrevious.js - Link
import { useRef, useEffect } from "react";
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
export { usePrevious };
The problem here is you set your reference to update through setState and useEffect (which is what causes you the infinite loop).
The way you would go by setting references on functional components would be as followed:
const Component = () => {
const ref = useRef(null)
return (
<div ref={ref} />
)
}
More info can be found here: https://reactjs.org/docs/refs-and-the-dom.html

how to add a classList in react using material UI

I'm trying to add a class to an element using Material UI in a scroll event like this.
const useStyles = makeStyles({
sticky: {
position: 'fixed',
top: 0,
width: '100%',
}
});
export default function myBar() {
React.useEffect(() => {
const myBar = document.getElementById("myBar");
const sticky = myBar.offsetTop;
const scrolling = window.addEventListener("scroll", () => {
if (window.pageYOffset > sticky) {
myBar.classList.add("sticky");
} else {
myBar.classList.remove("sticky");
}
});
return () => {
window.removeEventListener("scroll", scrolling);
};
}, []);
const classes = useStyles();
return (
<header id="myBar">
// some content
</header>
);
};
The problem is that Mterial Ui will generate some random numbers after class name, like sticky_123 so it will never be only sticky
Is it any way I can solve this problem?
The problem is that Material Ui will generate some random numbers after class name, like sticky_123 so it will never be only sticky
In order to use the className generated by Material UI, you must use classes.sticky instead of "sticky".
By the way, the component name should be in PascalCase.
const useStyles = makeStyles({
sticky: {
position: 'fixed',
top: 0,
width: '100%',
}
});
export default function MyBar() {
const classes = useStyles();
useEffect(() => {
const myBar = document.getElementById("myBar");
const sticky = myBar.offsetTop;
const scrollHandler = () => {
if (window.pageYOffset > sticky) {
myBar.classList.add(classes.sticky);
} else {
myBar.classList.remove(classes.sticky);
}
};
window.addEventListener("scroll", scrollHandler)
return () => {
window.removeEventListener("scroll", scrollHandler);
};
}, [classes]);
return (
<header id="myBar">
// some content
</header>
);
};

Move a square using the coordinate system in reactjs

I need to move this square using _dragTask() function, and i also need to do to it by using the coordinate system. Anyone can do that?
import React from 'react';
import './App.css';
class App extends React.Component {
componentDidMount() {
}
constructor(props) {
super(props);
this.state = {
MainContainer: {backgroundColor: "#282c34", display: "flex", minHeight: "100vh"},
ObjectMap: [],
}
this._createObject = this._createObject.bind(this);
this._createBox = this._createBox.bind(this);
this._buttonCreateBox1 = this._buttonCreateBox1.bind(this);
this._dragTask = this._dragTask.bind(this);
}
_createObject = (object) => {
var ObjectMap = this.state.ObjectMap;
ObjectMap.push(object);
this.setState({ObjectMap: ObjectMap});
}
_createBox = (style) => {
var object = {position: "absolute", top: this.state.positionX, left: this.state.positionY};
var styleObject = Object.assign({},
object, style
)
return (
<div style={styleObject} draggable="true" onDragEnd={(event) => {this._dragTask(event)}}>
</div>
);
}
_dragTask(event) {
event.persist();
this.setState({positionX: event.screenX, positionY: event.screenY}, () => { console.log("Page X:"+ this.state.positionX + " Page Y:" + this.state.positionY); });
}
_buttonCreateBox1 = () => {
this._createObject(this._createBox({backgroundColor: "white", width: "300px", height: "300px"}));
}
render() {
return (
<div style={this.state.MainContainer}>
<button type="button" onClick={ this._buttonCreateBox1 }>Click Me!</button>
{
this.state.ObjectMap.map((item, index) => {
return item
})
}
</div>
);
}
}
export default App;
Right now, the object it created by printed in the screen by the mainloop, and added to it by _createObject() function.
just change your _dragTask method to this
_dragTask(event) {
event.target.style.top = event.clientY + "px";
event.target.style.left = event.clientX + "px";
}
and change the style of the wrapper to have position: relative
constructor(props) {
super(props);
this.state = {
MainContainer: {
backgroundColor: "#282c34",
position: "relative",
display: "flex",
minHeight: "100vh"
},
ObjectMap: []
};
...
checkout this sandbox to see full example

Dropping Over a Component inside nested Drop Targets giving error

Here is my Container Class
Code on Sandbox
`import React, { Component } from "react";
import { DropTarget } from "react-dnd";
import Box from "./Box";
class Container extends Component {
state = {
Boxes: [
{ left: 60, top: 30, text: "ITEM_1" },
{ left: 100, top: 70, text: "ITEM_2" }
]
};
render() {
const { connectDropTarget } = this.props;
return connectDropTarget(
<div
className="container"
style={{ width: "100%", height: "100vh", background: "yellow" }}
>
{this.state.Boxes.map((box, index) => {
return (
<Box
id={index}
key={index}
left={box.left}
top={box.top}
text={box.text}
moveBox={this.moveBox}
/>
);
})}
</div>
);
}
moveBox(id, left, top) {
const allBoxes = this.state.Boxes;
const singleBox = this.state.Boxes[id];
singleBox.left = left;
singleBox.top = top;
const newBox = allBoxes.filter((box, index) => index !== id);
newBox.push(singleBox);
this.setState({ Boxes: newBox });
}
}
export default DropTarget(
"items",
{
// Spec Object Started
drop(props, monitor, component) {
const item = monitor.getItem();
const delta = monitor.getDifferenceFromInitialOffset();
const left = Math.round(item.left + delta.x);
const top = Math.round(item.top + delta.y);
component.moveBox(item.id, left, top);
}
}, //Spec Oject Ended Here
(connect, monitor) => ({
connectDropTarget: connect.dropTarget()
})
)(Container);
`
And Here is my Box Class
import React, { Component } from "react";
import { DragSource, DropTarget } from "react-dnd";
import flow from "lodash/flow";
let whichDragging = "items";
class Box extends Component {
state = {};
render() {
const { left, top, text, connectDragSouce, connectDropTarget } = this.props;
return connectDragSouce(
connectDropTarget(
<div
style={{
width: "20%",
border: "2px dotted black",
margin: "auto",
position: "relative",
top: top,
left: left
}}
>
{text}
</div>
)
);
}
}
export default flow(
DragSource(
whichDragging,
{
beginDrag(props, monitor, component) {
console.log(component);
const { left, top, text, id } = props;
return {
left,
top,
text,
id
};
}
},
(connect, monitor) => ({
connectDragSouce: connect.dragSource()
})
),
DropTarget(
whichDragging,
{
drop(props, monitor, component) {
whichDragging = "nested";
const item = monitor.getItem();
const delta = monitor.getDifferenceFromInitialOffset();
const left = Math.round(item.left + delta.x);
const top = Math.round(item.top + delta.y);
console.log("Logging");
console.log(component);
// whichDragging = "items";
}
},
(connect, monitor) => ({
connectDropTarget: connect.dropTarget()
})
)
)(Box);
Simple Dragging Dropping Working fine but when i drop item_1 over item_2 or vice versa i got error and my Component in drop shows DragDropContainer in console.log i want to get the id|key of component over which one component is dropped and not able to find any solution since 2 days any help will be appriciated.

Resources