Implementing a momentary indicator in React - reactjs

My goal is to have a save indicator that flashes a save icon when data has just been saved (not while it's being saved), as an indication to the user that their edit was successful. React seems better suited towards state than one-off "actions," but this was the best I was able to come up with:
import React, { PureComponent, PropTypes } from 'react';
import Radium from 'radium';
import moment from 'moment';
import { ContentSave as SaveIcon } from 'material-ui/svg-icons';
class SaveIndicator extends PureComponent {
getStyles = () => {
if (!this.props.saving) return { opacity: 0 };
return {
animation: 'x 700ms ease 0s 3 normal forwards',
animationName: saveAnimation,
};
};
render() {
return <div style={styles.root}>
<div style={{ display: 'flex' }}>
<div style={{ marginRight: 16 }}>
Last saved {moment(this.props.lastSaved).fromNow()}
</div>
<div
style={this.getStyles()}
onAnimationEnd={() => this.props.onIndicationComplete()}
>
<SaveIcon color="#666" />
</div>
</div>
</div>
}
}
const saveAnimation = Radium.keyframes({
'0%': { opacity: 0 },
'50%': { opacity: 1 },
'100%': { opacity: 0 },
});
const styles = {
root: {
display: 'inline-block',
},
};
SaveIndicator.defaultProps = {
saving: false,
};
SaveIndicator.propTypes = {
lastSaved: PropTypes.object.isRequired,
onIndicationComplete: PropTypes.func,
saving: PropTypes.bool,
};
export default Radium(SaveIndicator)
It works, but is there a way I could streamline this and make it even shorter?

How about this. I had a component a while back that needed something similar to what you're describing. I'll paste it in because it works fully but the strategy is kind of like this: pass in a time to start the animation. This prop triggers a function to start the animation which grabs the difference between that time and "now". It iteratively sets the state to close the gap between the initial time and now until it exceeds the passed in duration prop.
class SaveIndicator extends Component {
static propTypes = {
children: Types.element,
// time in milliseconds when the save is started; can change
indicationStartTime: Types.number.isRequired,
// time in milliseconds that the animation will take to fade
duration: Types.number,
// time in milliseconds to wait between renderings
frameRate: Types.number,
};
static defaultProps = {
duration: 7000,
frameRate: 100,
}
constructor(props) {
super(props);
this.state = { opacity: 0 };
}
componentDidMount() {
this.startAnimation();
}
componentWillReceiveProps({ indicationStartTime }) {
if (indicationStartTime !== this.props.indicationStartTime) {
this.startAnimation();
}
}
startAnimation() {
const { indicationStartTime, duration, frameRate } = this.props;
const now = new Date().getTime();
const newOpacity = 1 - ((now - indicationStartTime) / duration);
if (now - indicationStartTime < duration) {
this.setState({ opacity: newOpacity }, () =>
setTimeout(::this.startAnimation, frameRate)
);
} else {
this.setState({ opacity: 0 });
}
}
render() {
const { children } = this.props;
const { opacity } = this.state;
const style = { opacity };
return <div style={style}>{children}</div>;
}
}

Related

useTransition mounts new object instantly

I am trying to figure out how to utilise useTransition for page transitions (simple opacity change where first page fades out and new one fades in).
So far I have this small demo going https://codesandbox.io/s/sleepy-knuth-xe8e0?file=/src/App.js
it somewhat works, but weirdly. When transition starts new page is mounted instantly while old one starts animating. This causes various layout issues and is not behaviour I am after. Is it possible to have first element fade out and only then mount and fade in second element?
Code associated to demo
import React, { useState } from "react";
import "./styles.css";
import { useTransition, a } from "react-spring";
export default function App() {
const [initial, setInitial] = useState(true);
const transition = useTransition(initial, {
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 }
});
return (
<div>
{transition((style, initial) => {
return initial ? (
<a.h1 style={style}>Hello Initial</a.h1>
) : (
<a.h1 style={style}>Hello Secondary</a.h1>
);
})}
<button onClick={() => setInitial(prev => !prev)}>Change Page</button>
</div>
);
}
you can delay the start of the transition by waiting for the leave animation to complete.
const sleep = t => new Promise(res => setTimeout(res, t));
...
const transition = useTransition(initial, {
from: { position: "absolute", opacity: 0 },
enter: i => async next => {
await sleep(1000);
await next({ opacity: 1 });
},
leave: { opacity: 0 }
});
This delays the animation also for the very first time it is run. You can have a ref to keep track of whether the component has been rendered before or if it is its first time rendering, then you can skip sleep call if it's the first render.
OR
You can just simply provide trail config
const transition = useTransition(initial, {
from: { position: "absolute", opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 },
trail: 300
});
You need to add position: absolute and then you need to set the right position with css.
import React, { useState } from "react";
import "./styles.css";
import { useTransition, a } from "react-spring";
export default function App() {
const [initial, setInitial] = useState(true);
const transition = useTransition(initial, {
from: { position: 'absolute', opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 }
});
return (
<div>
{transition((style, initial) => {
return initial ? (
<a.h1 style={style}>Hello Initial</a.h1>
) : (
<a.h1 style={style}>Hello Secondary</a.h1>
);
})}
<button onClick={() => setInitial(prev => !prev)}>Change Page</button>
</div>
);
}

I am trying to implement a way to delete swappable items, but my delete method removes all the items instead of just the one that is clicked

I have two components, App.js which holds my "widget" layout and SwappableComponent.js which creates each swappable widget. I am trying to implement a delete function but when I click on the delete button what happens is it deletes all the swappable components instead of just the one that is clicked on. Any help would be appreciated.
import React, { Component } from 'react';
import Swappable from './components/SwappableComponent'
import './App.css';
import DataTable from './components/tableWidget';
import PropTypes from "prop-types";
import { withStyles } from "#material-ui/core/styles";
import Paper from "#material-ui/core/Paper";
import Grid from "#material-ui/core/Grid";
const styles = theme => ({
root: {
flexGrow: 1
},
paper: {
padding: theme.spacing.unit * 2,
textAlign: "center",
color: theme.palette.text.secondary
}
});
class App extends Component {
constructor(props) {
super(props);
this.state={
widgets:[
{id:1, content: <DataTable/>},
{id:2, content: "#2"},
{id:3, content: "#3"},
{id:4, content: "#4"}
]
}
}
deleteEvent=(index)=>{
const copyWidgets=Object.assign([],this.state.widgets);
copyWidgets.splice(index);
this.setState({
widgets:copyWidgets
})
}
render() {
const { classes } = this.props;
return (
<div className={classes.root}>
<Grid container spacing={24}>
{
this.state.widgets.map((widget,index)=>{
return(
<Grid item xs={12} sm={6}>
<Paper className={classes.paper}><Swappable id={widget.id} content={widget.content} delete={this.deleteEvent.bind(this,index)}/></Paper>
</Grid>
)
})
}
</Grid>
</div>
);
}
}
App.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(App);
import React, { Component } from 'react'
class Swappable extends Component {
constructor() {
super()
this.state = {
customFunc: null
}
}
allowDrop(ev) {
ev.preventDefault();
}
drag(ev, customFunc = null) {
ev.dataTransfer.setData("src", ev.target.id);
console.log(ev.target.parentNode, 'TARGET DRAGSTART')
this.setState({
initialParentNode: ev.target.parentNode
})
}
dragEnd(ev, customFunc = null) {
console.log(ev.target.parentNode, 'TARGET DRAGEND')
if (customFunc && (ev.target.parentNode != this.state.initialParentNode)) {
console.log('custom func')
this.props.customFunc()
}
}
drop(ev, dragableId, dropzoneId, customFunc = null, swappable = true) {
ev.preventDefault();
let src = document.getElementById(ev.dataTransfer.getData("src"));
let srcParent = src.parentNode;
let target = document.getElementById(dragableId);
console.log(src, 'dragged element');
console.log(srcParent, 'parent of dragged');
console.log(target, 'element to be swapped')
swappable ? this.swapElements(src, target, srcParent) : this.transferElement(src, dropzoneId)
}
swapElements(src, target, srcParent) {
target.replaceWith(src);
srcParent.appendChild(target);
}
transferElement(src, dropzoneId) {
let dropzone = document.getElementById(dropzoneId)
dropzone.appendChild(src);
}
render() {
const dropZoneStyle = {
width: '450px',
minHeight: '300px',
padding: '10px',
border: ''
};
const draggableStyle = {
width: '400px',
height: '300px',
padding: '10px',
border: ''
};
const { id, content, swappable, customFunc } = this.props
const dropzoneId = 'drop' + id
const dragableId = 'drag' + id
console.log(customFunc, 'customFunc')
return (
<div
id = {dropzoneId}
onDrop={(event) => this.drop(event, dragableId, dropzoneId, customFunc, swappable)}
onDragOver={(event) => this.allowDrop(event)}
style={dropZoneStyle}>
<div id={ dragableId }
draggable="true"
onDragStart={(event) => this.drag(event)}
onDragEnd = {(event) => this.dragEnd(event, customFunc)}
style={draggableStyle}>
{ content }
<button onClick={this.props.delete}>Delete</button>
</div>
</div>
)
}
}
export default Swappable;
The reason why all of the items are removed is that you didn't specify a second argument to the .splice function which is the number of items to delete from the array or the deleteCount.
From MDN docs:
If deleteCount is omitted, or if its value is equal to or larger than
array.length - start (that is, if it is equal to or greater than the
number of elements left in the array, starting at start), then all of
the elements from start through the end of the array will be deleted.
To fix it, modify your deleteEvent function to the following:
deleteEvent = (index) => {
const copyWidgets = Object.assign([], this.state.widgets);
copyWidgets.splice(index, 1); // delete one item only
this.setState({
widgets: copyWidgets
});
};
A simple example to show the different behaviour:
console.log('without using second argument with splice');
const letters = ['a', 'b', 'c'];
console.log('before', letters);
letters.splice(0);
console.log('after', letters);
console.log('using second argument with splice');
const numbers = [1, 2, 3];
console.log('before', numbers);
numbers.splice(1, 1);
console.log('after splice', numbers);

Changing styles when scrolling React

I want to add the scrolling effect. At the start, the elements have the opacity: 0.2 property. When element is reached in the browser window, it is to replace the property with opacity: 1. At this moment, when I scroll, all elements change the property to opacity: 1. How to make this value when element is reached in the browser, the rest of the elements have the property opacity: 0.2
class QuestionListItem extends Component {
constructor() {
super();
this.state = {
opacity: 0.2,
};
}
componentDidMount = () => {
window.addEventListener('scroll', () => {
this.setState({
opacity: 1,
});
});
};
render() {
const { question } = this.props;
const { opacity } = this.state;
return (
<div>
<li
key={question.id}
className="Test__questions-item"
style={{ opacity: `${opacity}` }}
ref={
(listener) => { this.listener = listener; }
}
>
<p>
{question.question}
</p>
<QuestionAnswerForm />
</li>
</div>
);
}
}
I want effect like this https://anemone.typeform.com/to/jgsLNG
A proper solution could look like this. Of course, this is just a concept. You can fine-tune the activation/deactivation logic using props from getBoundingClientRect other than top (e.g. height, bottom etc).
Important that you should not set the component's state on every single scroll event.
const activeFromPx = 20;
const activeToPx = 100;
class ScrollItem extends React.Component {
state = {
isActive: false
}
componentDidMount = () => {
window.addEventListener('scroll', this.handleScroll);
this.handleScroll();
};
handleScroll = () => {
const { top } = this.wrapRef.getBoundingClientRect();
if (top > activeFromPx && top < activeToPx && !this.state.isActive) {
this.setState({ isActive: true });
}
if ((top <= activeFromPx || top >= activeToPx) && this.state.isActive) {
this.setState({ isActive: false });
}
}
setWrapRef = ref => {
this.wrapRef = ref;
}
render() {
const { isActive } = this.state;
return (
<div
className={`scroll-item ${isActive && 'scroll-item--active'}`}
ref={this.setWrapRef}
>
{this.props.children}
</div>
)
}
}
class ScrollExample extends React.Component {
render() {
return (
<div className="scroll-wrap">
<ScrollItem>foo</ScrollItem>
<ScrollItem>bar</ScrollItem>
<ScrollItem>eh</ScrollItem>
</div>);
}
}
ReactDOM.render(<ScrollExample />, document.getElementById('root'))
.scroll-wrap {
height: 300vh;
background: lightgray;
padding-top: 55px;
}
.scroll-item {
height: 60vh;
background: lightcyan;
margin: 10px;
opacity: 0.2;
}
.scroll-item--active {
opacity: 1;
}
<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>
<div id="root"></div>
You can include an isInViewport-like implementation as this one: https://gist.github.com/davidtheclark/5515733 then use it on your component.
componentDidMount = () => {
window.addEventListener('scroll', (event) => {
if (isElementInViewport(event.target) {
this.setState({
opacity: 1,
});
}
});
};
There's also read-to-use react-addons for this: https://github.com/roderickhsiao/react-in-viewport

How to make a React Native animation happen again?

Currently, my React Native animation only happens one time then never again. I need it to happen every time one of my props for that component changes. I have the data display changing when the new prop data comes in but it only animates the first time. Is there a way for me to for the animation to happen again every time that props changes/the component updates?
Here is what I have so far:
import React from 'react';
import {Animated, Easing, StyleSheet, Text, View} from 'react-native';
//Animation
class FadeInView extends React.Component {
state = {
yAnimation: new Animated.Value(21),
}
componentDidMount() {
Animated.timing(
this.state.yAnimation,
{
//easing: Easing.bounce,
toValue: 0,
duration: 150,
}
).start();
}
render() {
let { yAnimation } = this.state;
return (
<Animated.View
style={{
...this.props.style,
transform: [{translateY: this.state.yAnimation}],
}}
>
{this.props.children}
</Animated.View>
);
}
}
//Price Component
export default class Price extends React.Component {
constructor(props) {
super(props);
this.animateNow = false;
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.price !== nextProps.price) {
console.log('true');
return true;
} else {
return false;
}
}
componentWillUpdate() {
if (this.props.price != this.localPrice) {
this.animateNow = true;
}
}
componentDidUpdate() {
this.localPrice = this.props.price;
this.animateNow = false;
console.log(this.props.price);
}
render() {
if (this.animateNow) {
return (
<FadeInView>
<Text style={styles.price}>{this.props.price}</Text>
</FadeInView>
);
} else {
return (
<View>
<Text style={styles.price}>{this.props.price}</Text>
</View>
);
}
}
}
const styles = StyleSheet.create({
price: {
fontFamily: 'Avenir',
fontSize: 21,
color: '#606060',
textAlign: 'right',
marginRight: 20,
backgroundColor: 'transparent'
}
});
If you want to animate again when receive props, you should call that again inside componentWillReceiveProps():
playAnimation() {
Animated.timing(
this.state.yAnimation,
{
toValue: 0,
duration: 150,
}
).start();
}
componentWillReceiveProps(next) {
if (next.props.changed) {
this.playAnimation();
}
}

react-dnd uncaught typerrors. Trying to follow the simple sortable example

I've been trying to work off of the simple sortable example in the react-dnd examples but I am having trouble trying to convert the es7 code to es6. I've tried using babel but I don't really understand the code that it spits out.
Here is my code that I've tried to translate from es7 to es6:
import React, {PropTypes} from 'react';
import Router from 'react-router';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import { DragSource, DropTarget } from 'react-dnd';
const style= {
border: '1px dashed gray',
padding: '0.5rem 1rem',
marginBottom: '.5rem',
backgroundColor: 'white',
cursor: 'move'
}
const ItemTypes = {
Coursepage: 'coursepage'
};
const coursePageSource = {
beginDrag(props) {
return {
id: props.id,
index: props.index
}
}
}
const coursePageTarget = {
hover(props, monitor, component){
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
//don't replace items with themselves
if(dragIndex === hoverIndex){
return;
}
//Determine rectangle on screen
const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();
//get vertical middle
const hoverMiddleY = (hoverBoundingRect.Bottom - hoverBoundingRect.Top) /2;
//get top pixels
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
//only perform the move when the mouse has crossed half of the items height
//when dragging downwards, only move when the cursor is below 50%
//when dragging upwards, only move when the cursor is above 50%
//dragging downwards
if(dragIndex < hoverIndex && hoverClientY < hoverMiddleY){
return;
}
//dragging upwards
if(dragIndex > hoverIndex && hoverClientY > hoverMiddleY){
return;
}
//time to actually perform the action
props.moveObject(dragIndex, hoverIndex);
}
}
// const propTypes = {
// connectDragSource: PropTypes.func.isRequired,
// connectDropTarget: PropTypes.func.isRequired,
// index: PropTypes.number.isRequired,
// isDragging: PropTypes.bool.isRequired,
// id: PropTypes.any.isRequired,
// text: PropTypes.string.isRequired,
// moveCard: PropTypes.func.isRequired
// };
function collectDropTarget(connect) {
return {
connectDropTarget: connect.dropTarget(),
};
}
/**
* Specifies which props to inject into your component.
*/
function collectDragSource(connect, monitor) {
return {
// Call this function inside render()
// to let React DnD handle the drag events:
connectDragSource: connect.dragSource(),
// You can ask the monitor about the current drag state:
isDragging: monitor.isDragging()
};
}
class Coursepage extends React.Component{
render(){
console.log(this.props);
const {text, isDragging, connectDragSource, connectDropTarget} = this.props;
const opacity = isDragging ? 0 : 1;
return connectDragSource(connectDropTarget(
<div style={{opacity}}>
{text}
</div>
));
}
}
// Coursepage.propTypes = propTypes;
export default DragSource(ItemTypes.Coursepage, coursePageSource, collectDragSource)(Coursepage);
export default DropTarget(ItemTypes.Coursepage, coursePageTarget, collectDropTarget)(Coursepage);
Now the error I'm getting from this is
"Uncaught TypeError: connectDropTarget is not a function."
I console logged this.props in render and I see that connectDragSource is showing up in the this.props object but not connectDropTarget.
Can anyone tell me what I'm missing?
By the way, this is the example code I was using:
https://github.com/gaearon/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js
I know this is a little old but I landed up here through google so I figured I would give it a go. First of all, you can't have two default exports as referenced here in section 3.2 http://www.2ality.com/2014/09/es6-modules-final.html
Instead you need to pass the result of one of your current default exports into the second function call - you'll see below.
This took me a couple of hours to get working as I'm also an Es6/7 newbie - so I invite any criticism!
// Container.js;
import React, { Component } from 'react';
import update from 'react/lib/update';
import Card from './Card';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
const style = {
width: 400
};
class Container extends Component {
constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.findCard = this.findCard.bind(this);
this.state = {
cards: [{
id: 1,
text: 'Write a cool JS library'
}, {
id: 2,
text: 'Make it generic enough'
}, {
id: 3,
text: 'Write README'
}, {
id: 4,
text: 'Create some examples'
}, {
id: 5,
text: 'Spam in Twitter and IRC to promote it (note that this element is taller than the others)'
}, {
id: 6,
text: '???'
}, {
id: 7,
text: 'PROFIT'
}]
};
}
findCard(id) {
const { cards } = this.state;
const card = cards.filter(c => c.id === id)[0];
return {
card,
index: cards.indexOf(card)
};
}
moveCard(id, atIndex) {
const { card, index } = this.findCard(id);
this.setState(update(this.state, {
cards: {
$splice: [
[index, 1],
[atIndex, 0, card]
]
}
}));
}
render() {
const { cards } = this.state;
return (
<div style={style}>
{cards.map((card, i) => {
return (
<Card key={card.id}
index={i}
id={card.id}
text={card.text}
moveCard={this.moveCard}
findCard={this.findCard} />
);
})}
</div>
);
}
}
export default DragDropContext(HTML5Backend)(Container)
Then Card.js
// Card.js
import React, { Component, PropTypes } from 'react';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
const style = {
border: '1px dashed gray',
padding: '0.5rem 1rem',
marginBottom: '.5rem',
backgroundColor: 'white',
cursor: 'move'
};
const cardSource = {
beginDrag(props) {
return {
id: props.id,
originalIndex: props.findCard(props.id).index
};
},
endDrag(props, monitor) {
const { id: droppedId, originalIndex } = monitor.getItem();
const didDrop = monitor.didDrop();
if (!didDrop) {
props.moveCard(droppedId, originalIndex);
}
}
};
const cardTarget = {
canDrop() {
return false;
},
hover(props, monitor) {
const { id: draggedId } = monitor.getItem();
const { id: overId } = props;
if (draggedId !== overId) {
const { index: overIndex } = props.findCard(overId);
props.moveCard(draggedId, overIndex);
}
}
};
function collect(connect, monitor) {
console.log( "HERE2", connect );
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop()
};
}
function collect2(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
connectDragPreview: connect.dragPreview(),
isDragging: monitor.isDragging()
};
}
class Card extends Component {
render() {
const { text, isDragging, connectDragSource, connectDropTarget } = this.props;
const opacity = isDragging ? 0 : 1;
return connectDragSource(connectDropTarget(
<div >
{text}
</div>
));
}
}
Card.propTypes = {
connectDragSource: PropTypes.func.isRequired,
connectDropTarget: PropTypes.func.isRequired,
isDragging: PropTypes.bool.isRequired,
id: PropTypes.any.isRequired,
text: PropTypes.string.isRequired,
moveCard: PropTypes.func.isRequired,
findCard: PropTypes.func.isRequired
};
const x = DropTarget(ItemTypes.CARD, cardTarget, collect )(Card)
export default DragSource(ItemTypes.CARD, cardSource, collect2 )( x )
And then the types include
// ItemTypes.js
export default {
CARD: 'card'
};

Resources