react-custom-scrollbars jumps to top on any action - reactjs

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>

Related

React-Beautiful-Dnd Can't Find Draggable Element with Id

I'm trying to replicate the react-beautiful-dnd tutorial step 4: reorder a list. I've copied the code in the tutorial as far as I can see exactly: https://egghead.io/lessons/react-reorder-a-list-with-react-beautiful-dnd
However, when I run react and try to drag the list items, I get errors like: Unable to find draggable element with id: task-1
If I look at the DOM, I can definitely see an element with that id:
I can't figure out what I'm doing wrong. I printed the id to console to check that it's a string, and it is. Thoughts?
INITIAL-DATA.JS
const initialData = {
tasks : {
"task-1" : { id : "task-1", content : "Take out garbage"},
"task-2" : { id : "task-2", content : "Watch show"},
"task-3" : { id : "task-3", content : "Charge phone"},
"task-4" : { id : "task-4", content : "Cook dinner"},
},
columns : {
"column-1" : {
id : "column-1",
title: "To Do",
taskIds : ["task-1", "task-2", "task-3", "task-4"]
}
},
columnOrder : ["column-1"]
};
export default initialData;
INDEX.JS
import React from 'react';
import ReactDOM from 'react-dom';
import initialData from "./initial-data";
import Column from "./column";
import { DragDropContext } from 'react-beautiful-dnd';
class App extends React.Component {
state = initialData;
// Needs to synchronously update our state to reflect the drag-drop result
// The only required DragDrop callback
onDragEnd = result => {
}
render() {
return (
<DragDropContext onDragEnd={this.onDragEnd}>
{
this.state.columnOrder.map( (columnId) => {
const column = this.state.columns[columnId];
const tasks = column.taskIds.map( taskId => this.state.tasks[taskId]);
return <Column key={column.id} column={column} tasks={tasks} />;
})
}
</DragDropContext>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
COLUMN.JS
import React from "react";
import styled from "styled-components";
import Task from "./task";
import { Droppable } from 'react-beautiful-dnd';
const Container = styled.div`
margin: 8px;
border: 1px solid lightgrey;
border-radius: 2px;
`;
const Title = styled.h3`
padding: 8px;
margin: 0px;
`;
const TaskList = styled.div`
padding: 8px;
`;
export default class Column extends React.Component {
render() {
return (
// Note: Droppables expect their child to be a function that returns a react component
<Container>
<Title>{this.props.column.title}</Title>
<Droppable droppableId={this.props.column.id}>
{ provided => (
// The droppableProps in the provided object (a react-beautiful-dnd object) need to get provided to the object
// you want to designate as your droppable
// {provided.placeholder} // Needs to be added as a child of the component you designate as the droppable
// ref is an attribute of -components. Returns the dom node of the component
<TaskList
ref={provided.innerRef}
{...provided.droppableProps}
>
{ this.props.tasks.map( (task, index) => <Task key={task.id} task={task} index={index} /> ) }
{provided.placeholder}
</TaskList>
)}
</Droppable>
</Container>
)
}
}
TASK.JS
import React from "react";
import styled from "styled-components";
import { Draggable } from 'react-beautiful-dnd';
const Container = styled.div`
border: 1px solid lightgrey;
border-radius: 2px;
padding: 8px;
margin-bottom: 8px;
background-color: white; /* so don't see through when dragging */
`;
export default class Task extends React.Component {
render() {
console.log(this.props.task.id)
console.log(typeof this.props.task.id)
return (
// Required draggable props are draggableId and index
// Note: Draggables expect their child to be a function that returns a react component
<Draggable draggableId={this.props.task.id} index={this.props.index}>
{ provided => (
// The draggbleProps in the provided object (a react-beautiful-dnd object) need to get provided to the object
// you want to designate as your draggable
// DragHandleProps needs to get applied to the part of that object that you want to use to drag the whole object
// ref is an attribute of -components. Returns the dom node of the component
<Container
ref={provided.innerRef}
{...provided.draggbleProps}
{...provided.dragHandleProps}
>
{ this.props.task.content }
</Container>
)}
</Draggable>
)
}
}
There is just a typo in your code: in task.js change {...provided.draggbleProps} to {...provided.draggableProps}
As seen above, the issue here was the typo. Per your comment below that answer, you could help avoid this in the future by using Typescript. It would have shown you an error in your editor at the typo, and also given you autocomplete.

How to integrate react DnD with react fullcalendar?

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.

How to pass Styled-Component theme variables to Components?

Within my React+StyledComponent app, I have a theme file like so:
theme.js:
const colors = {
blacks: [
'#14161B',
'#2E2E34',
'#3E3E43',
],
};
const theme = {
colors,
};
export default theme;
Currently, I can easily use these colors to style my components like so:
const MyStyledContainer = styled.div`
background-color: ${(props) => props.theme.colors.blacks[1]};
`;
The problem is, how do I pass blacks[1] to a Component as the prop of the color to use like so:
<Text color="black[1]">Hello</Text>
Where Text.js is:
const StyledSpan = styled.span`
color: ${(props) => props.theme.colors[props.color]};
`;
const Text = ({
color,
}) => {
return (
<StyledSpan
color={color}
>
{text}
</StyledSpan>
);
};
Text.propTypes = {
color: PropTypes.string,
};
export default Text;
Currently the above is silently failing and rending the following in the DOM:
<span class="sc-brqgn" color="blacks[1]">Hello</span>
Any ideas on how I can get this to work? Thank you
EDIT: Updated to use styled-components withTheme HOC
New answer
You could wrap the component rendering <Text> in the higher order component (HOC) withTheme provided by styled-components. This enables you to use the theme given to the <ThemeProvider> directly in the React component.
Example (based on the styled-components docs):
import React from 'react'
import { withTheme } from 'styled-components'
import Text from './Text.js'
class MyComponent extends React.Component {
render() {
<Text color={this.props.theme.colors.blacks[1]} />;
}
}
export default withTheme(MyComponent)
Then you could do
const MyStyledContainer = styled.div`
background-color: ${(props) => props.color};
`;
Old answer
You could import the theme where you render and pass <Text color={theme.blacks[1]} />.
import theme from './theme.js'
...
<Text color={theme.colors.blacks[1]} />
Then you could do
const MyStyledContainer = styled.div`
background-color: ${(props) => props.color};
`;
You can use defaultProps
import PropTypes from 'prop-types'
MyStyledContainer.defaultProps = { theme }
App.js
App gets theme and passes color to Text
import React, { Component } from 'react'
import styled from 'styled-components'
const Text = styled.div`
color: ${props => props.color || 'inherit'}
`
class App extends Component {
render() {
const { theme } = this.props
return (
<Text color={theme.colors.black[1]} />
)
}
}
export default App
Root.js
Root component passes theme to entire application.
import React, { Component } from 'react'
import { ThemeProvider } from 'styled-components'
import theme from './theme'
import App from './App'
class Root extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
)
}
}
export default Root
If you're using functional components in React and v4.x and higher styled-components, you need to leverage useContext and styled-components' ThemeContext. Together, these allow you to use your theme settings inside of components that aren't styled-components.
import { useContext } from 'react'
import { ThemeContext } from 'styled-components'
export default function MyComponent() {
// place ThemeContext into a context that is scoped to just this component
const themeProps = useContext(ThemeContext)
return(
<>
{/* Example here is a wrapper component that needs sizing params */}
{/* We access the context and all of our theme props are attached to it */}
<Wrapper maxWidth={ themeProps.maxWidth }>
</Wrapper>
</>
)
}
Further reading in the styled-components docs: https://styled-components.com/docs/advanced#via-usecontext-react-hook

Semantic UI React: how to add a transition to Popup?

I'm building a "hovering" menu, using semantic-ui-react's Popup, and want to add a simple show-hide transition, how it can be done?
this is probably coming in too late for this specific OP, but might be useful for someone else trying to figure same out.
I believe you can use the TransionablePortal as shown in the example. Just for fun, I adapted that example to what I think you are trying to do:
import React, { Component } from 'react'
import { Button, Menu, TransitionablePortal } from 'semantic-ui-react'
export default class TransitionablePortalExamplePortal extends Component {
state = { open: false }
handleOpen = () => this.setState({ open: true })
handleClose = () => this.setState({ open: false })
render() {
const { open } = this.state
return (
<TransitionablePortal
closeOnTriggerClick
onOpen={this.handleOpen}
onClose={this.handleClose}
transition={{animation: "fade left", duration: 500 }}
openOnTriggerClick
trigger={
<Button circular basic
icon="ellipsis vertical"
negative={open}
positive={!open}
/>
}
>
<Menu vertical style={{ right: '1%', position: 'fixed', top: '0%', zIndex: 1000}}>
<Menu.Item>Menu Item 1</Menu.Item>
<Menu.Item>Menu Item 2</Menu.Item>
</Menu>
</TransitionablePortal>
)}}
You should be able to make the transition use onMouseEnter and onMouseLeave if you want same transition to be on hover, instead of on click.
You can find in their official documentation example where you can make custom style for popup
import React from 'react'
import { Button, Popup } from 'semantic-ui-react'
const style = {
borderRadius: 0,
opacity: 0.7,
padding: '2em',
}
const PopupExampleStyle = () => (
<Popup
trigger={<Button icon='eye' />}
content='Popup with a custom style prop'
style={style}
inverted
/>
)
export default PopupExampleStyle
You can try to add transition property here

How to use the styled-component property innerRef with a React stateless component?

I have the following styled component:
const Component = styled.div`
...
`;
const Button = (props) => {
return (
<Component>
...
</Component>
);
};
export default styled(Button)``;
I want to get a reference to the underlying div of Component. When I do the following I get null:
import Button from './Button.js';
class Foo extends React.Component {
getRef = () => {
console.log(this.btn);
}
render() {
return (
<Button innerRef={elem => this.btn = elem} />
);
}
}
Any ideas why I am getting null and any suggestions on how to access the underlying div?
Note: The reason I am doing this export default styled(Button)``; is so that the export styled component can be easily extended.
I managed to accomplish this by passing a function down as a prop to the styled-component that I was targeting, then passing the ref back as an argument of the function:
const Component = styled.div`
...
`;
const Button = (props) => {
return (
<Component innerRef={elem => props.getRef(elem)}>
...
</Component>
);
};
export default styled(Button)``;
...
import Button from './Button.js';
class Foo extends React.Component {
getRef = (ref) => {
console.log(ref);
}
render() {
return (
<Button getRef={this.getRef} />
);
}
}
Passing a ref prop to a styled component will give you an instance of the StyledComponent wrapper, but not to the underlying DOM node. This is due to how refs work. So it's not possible to call DOM methods, like focus, on styled components wrappers directly.
Thus to get a ref to the actual, wrapped inner DOM node, callback is passed to the innerRef prop as shown in example below to focus the 'input' element wrapped inside Styled component 'Input' on hover.
const Input = styled.input`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
`;
class Form extends React.Component {
render() {
return (
<Input
placeholder="Hover here..."
innerRef={x => { this.input = x }}
onMouseEnter={() => this.input.focus()}
/>
);
}
}
render(
<Form />
);
NOTE:-
String refs not supported (i.e. innerRef="node"), since they're already deprecated in React.

Resources