How to integrate react DnD with react fullcalendar? - reactjs

I have the following simple demo for a drag and drop component using React DnD plugin.
Card.js (DropSource)
import React, { Component } from 'react';
import { DragSource } from 'react-dnd';
const ItemTypes = {
CARD: 'card'
};
const cardSource = {
beginDrag(props) {
return { };
}
}
function collect(connect, monitor) {
return {
connectDragSource : connect.dragSource(),
connectDragPreview: connect.dragPreview(),
isDragging : monitor.isDragging()
}
}
class Card extends Component {
render() {
const { connectDragSource , isDragging } = this.props;
return connectDragSource(
<div style={{
opacity : isDragging ? 0.5 : 1,
height: '50px',
width: '50px',
backgroundColor: 'orange',
}}>
♞
</div>
);
}
}
export default DragSource(ItemTypes.CARD, cardSource , collect)(Card);
Box.js (Droptarget)
import React, { Component } from 'react';
import { DropTarget } from 'react-dnd';
const boxTarget = {
canDrop(props) {
},
drop(props) {
}
};
function collect(connect, monitor) {
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop()
};
}
const ItemTypes = {
CARD: 'card'
};
class Box extends Component {
render() {
const { connectDropTarget, isOver, canDrop } = this.props;
return connectDropTarget(
<div style={{
position: 'relative',
width: '200px',
height: '200px',
background: canDrop ? '#ff0000' : '#eee'
}}>
{ this.props.children }
</div>
);
}
}
export default DropTarget(ItemTypes.CARD, boxTarget, collect)(Box);
simpleDrag.js
import React, { Component } from 'react';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import CARD from './card';
import BOX from './box';
class simpleDrag extends Component {
render() {
return(
<div>
<BOX />
<CARD/>
</div>
);
}
}
export default DragDropContext(HTML5Backend)(simpleDrag);
And then ofcourse i use the simpleDrag element in my app.js to render and i have a working DnD example , now my question is how can i use DnD along site fullcalender.js ? I.E. say i want to make each day cell in the full calender a dropable target how do i do that ?
Fullcalender.js
React DnD
The above code can be found in my github repo HERE.

You can integrate fullcalendar and react-dnd using the ThirdPartyDraggable interface provided by fullcalendar (docs).
However, it is important to notice that fullcalendar reacts to mouse events to implement its drag and drop. react-dnd provides the a html5-backend, but they don't play together nicely as the HTML5 Drag and Drop API disables mouse events in favour of drag events.
You should thus use an alternative backend that uses those mouse events. E.g. this one.
I implemented a sandbox with an example implementation.

for the record, hooks (which React is about in functional components) cannot be used in class-based components (https://reactjs.org/warnings/invalid-hook-call-warning.html).
You might want to consider rewriting your Card and Box as RFCs instead of RCCs.

Related

React Native: hooks can only be called inside of the body of a function component

code:
import React, { Component } from 'react'
import {
View,
Text,
TextInput
} from 'react-native'
export default class Home extends Component {
static navigationOptions = ({ navigation }) => {
return {
title: 'Home'
}
}
render () {
const [value, onChangeText] = React.useState('Useless Placeholder');
return (<View>
<Text>Home</Text>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => onChangeText(text)}
value={value}
/>
</View>);
}
}
Learning React Native, encountered this error, how to correct the above code?
The official example of my imitation: https://reactnative.cn/docs/textinput
You are using class component and hooks can only be used in functional components.
Either use setState or convert the class to functional, like so
export default const Home = props => {
// your code
}
Moreover, it is not a good idea to set state inside the render, so you should take it outside.

react-custom-scrollbars jumps to top on any action

I am using react-custom-scrollbars in a react web app because I need to have two independant scroll bars, one for the main panel and one for the drawer panel. My issue is that the content in the main panel is dynamic and whenever I take some action in the main panel that changes state the scroll bar jumps to the top of the panel again.
UPDATE:
I believe I need to list for onUpdate and handle the scroll position there. If it has changed then update if not do not move the position?
In code, I have a HOC call withScrollbar as follows:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import AutoSizer from 'react-virtualized-auto-sizer';
import { Scrollbars } from 'react-custom-scrollbars';
import { colors } from '../../theme/vars';
import { themes } from '../../types';
// This is a Higher Order Component (HOC) used to
// provide a scroll bar to other components
export default (ChildComponent, styling) => {
class ComposedComponent extends Component {
state = {
// position: ??
};
handleUpdate = () => {
//update position
//this.scrollbar.scrollToBottom();
};
render() {
return (
<AutoSizer>
{
({ width, height }) => (
<Scrollbars
style={{ width, height, backgroundColor: colors.WHITE, overflow: 'hidden', ...styling }}
onUpdate={() => this.handleUpdate()}
renderThumbVertical={props => <Thumb {...props} />}
autoHide
autoHideTimeout={1000}
autoHideDuration={200}
>
<ChildComponent {...this.props} />
</Scrollbars>
)
}
</AutoSizer>
);
}
}
return ComposedComponent;
};
const Thumb = styled.div`
background-color: ${props =>
props.theme.theme === themes.LIGHT ? colors.BLACK : colors.WHITE};
border-radius: 4px;
`;
in my MainView component I just wrap the export like this:
export default withScrollbar(LanguageProvider(connect(mapStateToProps, null)(MainView)));
I have read a few similar issues on this like this one: How to set initial scrollTop value to and this one scrollTo event but I cannot figure out how to implement in my case. Any tips or suggestions are greatly appreciated.
So I found a way to get this to work and it feels like a complete hack but I'm posting in hopes it might help someone else.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import AutoSizer from 'react-virtualized-auto-sizer';
import { Scrollbars } from 'react-custom-scrollbars';
import { colors } from '../../theme/vars';
import { themes } from '../../types';
// This is a Higher Order Component (HOC) used to
// provide a scroll bar to other components
export default (ChildComponent, styling) => {
class ComposedComponent extends Component {
state = {
stateScrollTop: 0,
};
onScrollStart = () => {
if (this.props.childRef) { // need to pass in a ref from the child component
const { scrollTop } = this.props.childRef.current.getValues();
const deltaY = Math.abs(scrollTop - this.state.stateScrollTop);
if (deltaY > 100) { // 100 is arbitrary. It should not be a high value...
this.props.childRef.current.scrollTop(this.state.stateScrollTop);
}
}
};
handleUpdate = () => {
if (this.props.childRef) {
const { scrollTop } = this.props.childRef.current.getValues();
this.setState({ stateScrollTop: scrollTop });
}
};
render() {
return (
<AutoSizer>
{
({ width, height }) => (
<Scrollbars
ref={this.props.childRef}
style={{ width, height, backgroundColor: colors.WHITE, overflow: 'hidden', ...styling }}
onScrollStart={e => this.onScrollStart(e)}
onUpdate={e => this.handleUpdate(e)}
renderThumbVertical={props => <Thumb {...props} />}
autoHide
autoHideTimeout={1000}
autoHideDuration={200}
>
<ChildComponent {...this.props} />
</Scrollbars>
)
}
</AutoSizer>
);
}
}
return ComposedComponent;
};
const Thumb = styled.div`
background-color: ${props =>
props.theme.theme === themes.LIGHT ? colors.BLACK : colors.WHITE};
border-radius: 4px;
`;
I use this HOC like this:
create a ref for the component you want to use it with
pass the ref to the component that will use the HOC:
class SomeChildComponent extends Component {
...
viewRef = React.createRef();
...
render() {
return ( <MainView childRef={this.viewRef} />)
}
import and wrap the component
import withScrollbar from '../../hoc/withScrollbar';
...
export default withScrollbar(MainView);
I tried the above solution and it didn't seem to work for me.
However what did work was making sure that my child components inside Scrollbars were wrapped in a div with a height of 100%:
<Scrollbars>
<div style={{ height: '100%' }}>
<ChildComponent />
<ChildComponent />
</div>
</Scrollbars>

Material-UI withStyles not adding classes to props

I'm trying to implement some styling using Material-UI's withStyles method, however I'm not able to get classes as a prop. Any suggestions as to what I'm missing? I've included the relevant code below, but note that there is an <App> component in this file that I'm leaving out for brevity.
import React from 'react'
import ReactDOM from "react-dom";
import {Paper, Typography} from '#material-ui/core'
import {withStyles} from '#material-ui/core/styles'
import NavBar from "./navBar";
class Recipe extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log('Recipe Did Mount')
}
render() {
const {recipeData, classes} = this.props;
return (
<Paper>
<Typography className={classes.recipeName}>{recipeData.name}</Typography>
<Typography className={classes.recipeIngredients}>{recipeData.ingredients}</Typography>
<Typography className={classes.recipeInstructions}>{recipeData.instructions}</Typography>
</Paper>
)
}
}
const styles = {
root: {
fontSize: "1.0rem",
margin: "0px"
},
recipeName: {
fontSize: "1.0rem",
margin: "0px"
},
recipeIngredients: {
fontSize: "1.0rem",
margin: "0px" },
recipeInstructions: {
fontSize: "1.0rem",
margin: "0px" }
};
withStyles(styles)(Recipe);
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<App/>,
document.body.appendChild(document.createElement('div')),
)
});
Since you aren't setting withStyles(styles)(Recipe); into a variable, I suspect you must be using Recipe directly within App.
withStyles doesn't change Recipe. withStyles creates a new component that wraps Recipe and passes the classes prop to it. In order to see the classes prop, you need to use the newly-created component with something like the following:
const StyledRecipe = withStyles(styles)(Recipe);
const App = ()=> {
return <StyledRecipe/>;
}
Assuming App is defined in a separate file (for others who may come looking for this question), change the
`withStyles(styles)(Recipe);`
To
export default withStyles(styles)(Recipe);
As Ryan already explained ' withStyles is the higher order component that creates and returns a new component'

React Child and Parent Components state change on click

I am trying to make a click on a button of a child React component change the Boolean state of the child and of its parent.
The issue here is that it has to change states of both components.
Here is a link for the code I am trying to get working:
https://stackblitz.com/edit/child-to-parent-state-pass-bkmvwc?file=Child.js
The requirement is to click the hamburger button and it changes the state of the child component (the actual hamburger button) and its parent component.
Thank you!
I would not recommend doing what you are doing.
But, knowing nothing of your background I will only answer your question.
In parent.js you are missing the bind to this.
Use this line instead and check if this works
Why don't you manage the state from the parent component like:
Parent.js:
import React from 'react'
import { Link } from 'react-router-dom'
import { initializeIcons } from '#uifabric/icons';
import Hamburger from './Child'
initializeIcons();
export default class NavBar extends React.Component {
constructor(props) {
super(props);
this.state = {
opened: false
};
}
handleCounter = () => {
this.setState({ opened: !this.state.opened });
}
render() {
return (
<Hamburger
opened={this.state.opened}
handleCounter={this.handleCounter}
/>
);
}
}
Child.js
import React from 'react'
import { IconButton } from 'office-ui-fabric-react/lib/Button';
import { initializeIcons } from '#uifabric/icons';
initializeIcons();
export default class Hamburger extends React.Component {
constructor(props) {
super(props);
}
updateParent() {
this.props.handleCounter(this.state);
}
render() {
return (
<IconButton
checked={this.props.opened}
iconProps={{ iconName: (this.props.opened ? 'Cancel' : 'GlobalNavButton'), style: { fontSize: 35 } }}
className="hamburger mobile-only"
title="Open Global Navigation"
ariaLabel="Open Global Navigation"
styles={{
root: {
padding: '0',
border: 'none',
background: 'transparent !important'
}
}}
onClick={this.props.handleCounter}
/>
);
}
}
PS: I removed the comments for readability
You would only change the state of the parent. The child would just read the props that are passed to it.
Parent component
constructor(props){
super(props)
this.state = {
hamburgerOpen: false
}
}
handleHamburgerToggle = () => {
let { hamburgerOpen } = this.state;
this.setState({
hamburgerOpen: !hamburgerOpen
})
}
render() {
let { hamburgerOpen } = this.state;
return (
<Child
hamburgerOpen={hamburgerOpen}
handleHamburgerToggle={this.handleHamburgerToggle}
/>
)
}
Child will have access to the props passed to it. You can make the Hamburger a functional component as well since it isn't concerned about the current state, only the parent is.
hamburgerOpen and toggleHamburgerOpen
Child Component
const { handleHamburgerToggle } = this.props;
return {
<div>
<div
onClick={() => handleHamburgerToggle()}
>
Click me to toggle hamburger
</div>
</div>
}

Embed Typeform in React app

How can I embed a Typeform form in my React app?
The embed code that Typeform provide doesn't compile in JSX.
This is a sample of the embed code:
<div class="typeform-widget" data-url="https://sample.typeform.com/to/32423" style="width: 100%; height: 500px;"></div> <script> (function() { var qs,js,q,s,d=document, gi=d.getElementById, ce=d.createElement, gt=d.getElementsByTagName, id="typef_orm", b="https://embed.typeform.com/"; if(!gi.call(d,id)) { js=ce.call(d,"script"); js.id=id; js.src=b+"embed.js"; q=gt.call(d,"script")[0]; q.parentNode.insertBefore(js,q) } })() </script> <div style="font-family: Sans-Serif;font-size: 12px;color: #999;opacity: 0.5; padding-top: 5px;"> powered by Typeform </div>
You can use a React wrapper component I created: https://github.com/alexgarces/react-typeform-embed
It uses the official Typeform Embed SDK under the hood. Basically you have to pass your form url, but it also supports other SDK options.
import React from 'react';
import { ReactTypeformEmbed } from 'react-typeform-embed';
class App extends React.Component {
render() {
return <ReactTypeformEmbed url="https://demo.typeform.com/to/njdbt5" />;
}
}
You can view Typeform documentation for embedding with JavaScript here.
And their official npm module here.
Use React refs to trigger initialisation similarly to how you would initialise a jQuery plugin for instance.
import React from 'react';
import * as typeformEmbed from '#typeform/embed'
class Form extends React.Component {
constructor(props) {
super(props);
this.el = null;
}
componentDidMount() {
if (this.el) {
typeformEmbed.makeWidget(this.el, "https://sample.typeform.com/to/32423", {
hideFooter: true,
hideHeaders: true,
opacity: 0
});
}
}
render() {
return (
<div ref={(el) => this.el = el} style={{width: '100%', height: '300px'}} />
)
}
}
export default Form;
Inspired by Elise Chant's solution and using function based components, hooks and Typescript, this is what I come up with for my project. I did not want to install another thin wrapper on top of the official SDK.
import * as typeformEmbed from '#typeform/embed';
import React, { useEffect, useRef } from 'react';
interface EmbeddedTypeformProps {
link: string;
hideFooter?: boolean;
hideHeaders?: boolean;
opacity?: number;
}
export const EmbeddedTypeform: React.FunctionComponent<EmbeddedTypeformProps> = ({
link,
hideFooter = true,
hideHeaders = true,
opacity = 90,
}) => {
const elementRef = useRef(null);
useEffect(() => {
typeformEmbed.makeWidget(elementRef.current, link, {
hideFooter,
hideHeaders,
opacity,
});
}, [link]);
return (
<div
ref={elementRef}
style={{ width: '100%', height: '100%', flex: '1 1 auto' }}
/>
);
};
If you are using Typescript with react and you got this error just make sure that noImplicitAny set to false in tsconfig file :
"noImplicitAny": false,

Resources