How to transform/animate with Chakra-UI? - javascript

Started using chakra-ui, and really loving it so far, but I'm struggling to figure out how to do a simple animation.
I have an image that i want to increase it's size onClick.
I've briefly looked at framer-motion but it seems a bit overkill for what i need.
I tried it anyways and kept getting an error when trying to define motionBox with typescript:
import { Flex, Container, HStack, Box, BoxProps } from "#chakra-ui/react";
import { motion } from "framer-motion";
const MotionBox = motion < BoxProps > Box;
errors:
Operator '>' cannot be applied to types 'boolean' and 'ChakraComponent<"div", {}>'.ts(2365)
'BoxProps' only refers to a type, but is being used as a value here.ts(2693)
Is there a simple way to animate with chakra? or should i just try to figure out my errors with framer?

I figured out a solution using state:
Whilst it's not technically animated, it does what i need.
(I also got framer working, creating a custom motion component, but using JS not TS)
const [size, setSize] = useState("20vh");
const toggleSize = () => {
if (size === "20vh") {
setSize("50vh");
} else {
setSize("20vh");
}
};
<Image
p="5px"
alt={product.id}
src={product.img[1]}
w={size}
maxH="50vh"
m="auto"
borderRadius="10px"
onClick={() => toggleSize()}
/>

transition="all .25s ease"
_hover={{
transform: 'scale(1.33)',
filter: "brightness(120%)",
}}

Related

toDataURL causing canvas to go blank until clicked

I have a strange bug. I have a React app that is using fabricjs. I can render things onto the canvas just fine, but when I try to save the canvas as an image, a strange bug occurs: after canvas.toDataURL is called, the entire canvas goes blank until the user clicks on one of the elements on the canvas itself, after which all elements will reappear.
The url created by toDataURL works fine: downloading this file will produce the expected image with all of the elements rendered
Here is a fiddle that demonstrates this behavior:
https://jsfiddle.net/db1gc45p/22/
const {useState, useEffect, useRef, useCallback} = React;
const useFabric = (onChange) => {
const fabricRef = useRef();
const disposeRef = useRef();
return useCallback(
(node) => {
if (node) {
fabricRef.current = new fabric.Canvas(node);
if (onChange) {
disposeRef.current = onChange(fabricRef.current);
}
} else if (fabricRef.current) {
fabricRef.current.dispose();
if (disposeRef.current) {
disposeRef.current();
disposeRef.current = undefined;
}
}
},
[onChange]
);
};
function Example() {
const ref = useFabric((canvas) => {
canvas.add(new fabric.Text("hello"))
canvas.toDataURL()
});
return (
<div style={{ display: "inline-block", border: "solid" }}>
<canvas
ref={ref}
width={100}
height={100}
/>
</div>
);
}
ReactDOM.render( <Example />, document.getElementById('root') );
You can see the bug for yourself. By commenting/uncommenting line 30 canvas.toDataURL(), you can see that the canvas element stays visible when we don't call canvas.toDataURL()
However, even if we do call canvas.toDataURL(), we can get the element to re-appear by clicking on it on the canvas.
How can I prevent all of the elements from going invisible?
Fabric.js does some rendering updates asynchronously, similar issue, however you can force a synchronous update (after doing something that triggers the async update) by using canvas.renderAll().
Try
function Example() {
const ref = useFabric((canvas) => {
canvas.add(new fabric.Text("hello"))
canvas.renderAll()
canvas.toDataURL()
});

Update leaflet-map when user clicks on map and new data is added

I am developing a React app on my Ubuntu 20.4 VM machine in a chrome Version 100.0.4896.127 (Official Build) (64-bit) browser.
For creating the polygons I use "h3-js". h3-js can only be added via npm as the the core library is transpiled from C using emscripten.
I want to implement the following: When I set a marker I would like to show the hexagon that are in the data array.
Setting the marker works fine. Also adding the data.
I do this the following way:
Setting the marker
<MapContainer
// center={[40.0151, -105.2921]}
center={[40.7579747, -73.9877313]}
// #ts-ignore
// onClick={addMarker}
zoom={15}
style={{ height: "90%" }}
// #ts-ignore
onZoomEnd={console.log}
>
<SetMarker />
<TileLayer
url="https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png"
maxZoom={19}
/>
{Object.entries(groups).map(([weight, polygons]) => {
const color = getColor(weight);
return (
<Polygon
key={weight}
positions={polygons}
pathOptions={{
...baseStyle,
fillColor: color,
color: color, // stroke color
weight: 0 // stroke weight
}}
/>
);
})}
</MapContainer>
The functional component <SetMarker />, sets my marker the following:
function SetMarker() {
console.log("set marker");
const [position, setPosition] = useState(null);
const map = useMapEvents({
click(e) {
setPosition(e.latlng);
}
});
// render hexagon
if (position !== null) {
data.pop(); // delete the last element that was added before the click
data.push([position.lat, position.lng]); // add new element
}
return position === null ? null : (
<div>
<Marker position={position}>
<Popup>You are here</Popup>
</Marker>
</div>
);
}
In the data array are all my coordinates stores that create my hexagons.
However, when clicking the map the marker is set, but the map does not re-render.
I have created the following app:
https://codesandbox.io/s/react-leaflet-map-with-marker-forked-0uexf6
Sorry that I do not use the inbuilt stackoverflow editor as h3-js has to be installed via npm and cannot added via a cdn.
How can I update my leaflet map and show the polygon on the location where the user clicked.
Any suggestions what I am doing wrong?
I appreciate your replies!
The component doesn't rerender because react is not tracking the data that you're importing. You can use that data to initialize a react state and use it to render your hexagons.
const [mapData, setMapData] = useState(data);
[...mapData].forEach((point) => {
and add a new item to that state every time the position changes inside your SetMarker component
function SetMarker({ setMapData }) {
...
useEffect(() => {
if (position !== null) {
setMapData((prevMapData) => [
...prevMapData,
[position.lat, position.lng]
]);
}
}, [position, setMapData]);
// render hexagon
...
}
and don't forget to pass the setter in the component props
<SetMarker setMapData={setMapData} />
You can see it working here https://codesandbox.io/s/react-leaflet-map-with-marker-answer-ycm2u0?file=/Map.js
As an additional note, your code generally does not follow react's good practices about immutability. I'd recommend you revisit the official documentation and adjust your code accordingly. Every time you use an imperative js function like pop, push, or set is a red flag. Personally, learning redux helped me to understand more immutability; Dan's courses in egghead are a good start https://egghead.io/q/resources-by-dan-abramov

How to implement a draggable React component

I'm getting back into React and am wanting to have some components which can be dragged around by the user on the website I'm making. Note, by draggable I mean 'moved around the page by mouse', not the 'drag and drop' kind of draggable.
My code so far kind of works but is a bit jerky and does not always register when the mouse is up/released.
This is the component I'm trying to make draggable.
import React from 'react';
export default class Folder extends React.Component {
constructor(props) {
super(props);
this.state = {mouseDown: false,
name: props.name,
left: props.left,
top:props.top
};
}
// mouse down -> grab coords and offset
// mouse move, if mouse down true, make mouse coords
// folder coords
// on mouse up change mouse down to false.(can't move)
mouseHandler(e){
this.setState({mouseDown: true})
}
mouseMove(e){
if(!this.state.mouseDown){
return
}else{
console.log('mouse held and moving')
let newLeft = e.clientX - e.nativeEvent.offsetX
let newTop = e.clientY - e.nativeEvent.offsetY
this.setState({left: newLeft, top:newTop})
}
}
mouseUp(e){
this.setState({mouseDown: false})
console.log('mouse up')
}
render() {
return (<div className="icon"
onMouseDown={(e) => this.mouseHandler(e)}
onMouseMove={(e) => this.mouseMove(e)}
onMouseUp={(e) => this.mouseUp(e)}
style={{top: this.state.top, left: this.state.left}} >
<div className="tab"></div>
<div className="foldergap"></div>
<div className="foldertitle"><p>{this.state.name}</p>/div>
</div>)
}
};
I know there are libraries I could use but I would like to use my own work where I can. I have also seen this similar question but the answers either seemed to use outdated techniques, DOM manipulation (which doesn't seem like the 'React way') or libraries.
My question is what am I doing wrong and what is the recommended way of achieving this functionality?
Thank you.

Canvas flickering when reactjs re-renders

I've got a problem using React JS and canvas together.
everything seems to work smooth, but when render method is called due to changes in other part of my app canvas flicker. It seems that react is re-appending it into the DOM (maybe because I'm playing an animation on it and its drawn frame is different each time).
This is my render method:
render: function() {
var canvasStyle = {
width: this.props.width
};
return (
<canvas id="interactiveCanvas" style={canvasStyle}/>
);
}
As a temporal solution I append my canvas tag manually, without reactjs:
render: function() {
var canvasStyle = {
width: this.props.width
};
return (
<div id="interactivediv3D">
</div>
);
}
And then:
componentDidMount: function() {
var canvasStyle = {
width: this.props.width
};
var el = document.getElementById('interactivediv3D');
el.innerHTML = el.innerHTML +
'<canvas id="interactive3D" style={'+canvasStyle+'}/>';
},
And it works right. But I think this is not a clean way and it's better to render this canvas tag using reactjs.
Any idea of how can I solve the problem? or at least avoiding reactjs re-rendering this canvas when only the drawn frame changed.
I spent time observing with your advice in mind and I find out this flickering was caused by the fact that I was accessing the canvas DOM element and changing canvas.width and canvas.height every time onComponentDidUpdate was called.
I needed to change this property manually because while rendering I don't know canvas.width yet. I fill style-width with "100%" and after rendering I look at "canvas.clientWidth" to extract the value in pixels.
As explained here: https://facebook.github.io/react/tips/dom-event-listeners.html I attached resize event and now I'm changing canvas properties only from my resizeHandler.
Re-rendering the entire tree shouldn't cause your canvas to flicker. But if you think that re-rendering is causing this issue, you could use shouldComponentUpdate lifecycle function and return false whenever you don't want to to update.
https://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate
So for example:
shouldComponentUpdate: function(nextProps, nextState) {
return false;
}
Any component with the above function defined will not ever run render more than once (at component mounting).
However I've not been able to replicate the flickering issue you complain of. Is your entire tree rendering too often perhaps? In which case the above will fix your canvas, but you should take a look at how many times and how often you are re-rendering your entire tree and fix any issues there.
I had the same problem. I used react-konva library and my component structure looked something like this: canvas had a background image <SelectedImage /> which flicked every time any state property changed.
Initial code
import React, { useState } from "react";
import { Stage, Layer, Image } from "react-konva";
import useImage from "use-image";
function SomeComponent() {
const [imgWidth, setImgWidth] = useState(0);
const [imgHeight, setImgHeight] = useState(0);
//...and other state properties
const SelectedImage = () => {
const [image] = useImage(imgSRC);
if (imgWidth && imgHeight) {
return <Image image={image} width={imgWidth} height={imgHeight} />;
}
return null;
};
return (
<div>
<Stage width={imgWidth} height={imgHeight}>
<Layer>
<SelectedImage />
{/* some other canvas components*/}
</Layer>
</Stage>
</div>
);
}
export default SomeComponent;
The solution
The problem was in a wrong structure of SomeComponent where one component was initialized inside another. In my case it was <SelectedImage /> inside of SomeComponent. I took it out to a separate file and flickering disappeared!
Here is a correct structure
SelectedImage.js
import React from "react";
import { Image } from "react-konva";
import useImage from "use-image";
function SelectedImage({ width, height, imgSRC }) {
const [image] = useImage(imgSRC);
if (width && height) {
return <Image image={image} width={width} height={height} />;
}
return null;
}
export default SelectedImage;
SomeComponent.js
import React, { useState } from "react";
import { Stage, Layer, Image } from "react-konva";
import SelectedImage from "./SelectedImage";
function SomeComponent() {
const [imgWidth, setImgWidth] = useState(0);
const [imgHeight, setImgHeight] = useState(0);
//...and other state properties
return (
<div>
<Stage width={imgWidth} height={imgHeight}>
<Layer>
<SelectedImage width={imgWidth} height={imgHeight} imgSRC={imgSRC} />
{/* some other canvas components*/}
</Layer>
</Stage>
</div>
);
}
export default SomeComponent;

How to auto-slide the window out from behind keyboard when TextInput has focus?

I've seen this hack for native apps to auto scroll the window, but wondering best way to do it in React Native... When a <TextInput> field gets focus and is positioned low in the view, the keyboard will cover up the text field.
You can see this issue in example UIExplorer's TextInputExample.js view.
Does anyone have a good solution?
2017 Answer
The KeyboardAvoidingView is probably the best way to go now. Check out the docs here. It is really simple compared to Keyboard module which gives Developer more control to perform animations. Spencer Carli demonstrated all the possible ways on his medium blog.
2015 Answer
The correct way to do this in react-native does not require external libraries, takes advantage of native code, and includes animations.
First define a function that will handle the onFocus event for each TextInput (or any other component you would like to scroll to):
// Scroll a component into view. Just pass the component ref string.
inputFocused (refName) {
setTimeout(() => {
let scrollResponder = this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(this.refs[refName]),
110, //additionalOffset
true
);
}, 50);
}
Then, in your render function:
render () {
return (
<ScrollView ref='scrollView'>
<TextInput ref='username'
onFocus={this.inputFocused.bind(this, 'username')}
</ScrollView>
)
}
This uses the RCTDeviceEventEmitter for keyboard events and sizing, measures the position of the component using RCTUIManager.measureLayout, and calculates the exact scroll movement required in scrollResponderInputMeasureAndScrollToKeyboard.
You may want to play around with the additionalOffset parameter, to fit the needs of your specific UI design.
Facebook open sourced KeyboardAvoidingView in react native 0.29 to solve this problem. Documentation and usage example can be found here.
We combined some of the code form react-native-keyboard-spacer and the code from #Sherlock to create a KeyboardHandler component that can be wrapped around any View with TextInput elements. Works like a charm! :-)
/**
* Handle resizing enclosed View and scrolling to input
* Usage:
* <KeyboardHandler ref='kh' offset={50}>
* <View>
* ...
* <TextInput ref='username'
* onFocus={()=>this.refs.kh.inputFocused(this,'username')}/>
* ...
* </View>
* </KeyboardHandler>
*
* offset is optional and defaults to 34
* Any other specified props will be passed on to ScrollView
*/
'use strict';
var React=require('react-native');
var {
ScrollView,
View,
DeviceEventEmitter,
}=React;
var myprops={
offset:34,
}
var KeyboardHandler=React.createClass({
propTypes:{
offset: React.PropTypes.number,
},
getDefaultProps(){
return myprops;
},
getInitialState(){
DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{
if (!frames.endCoordinates) return;
this.setState({keyboardSpace: frames.endCoordinates.height});
});
DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{
this.setState({keyboardSpace:0});
});
this.scrollviewProps={
automaticallyAdjustContentInsets:true,
scrollEventThrottle:200,
};
// pass on any props we don't own to ScrollView
Object.keys(this.props).filter((n)=>{return n!='children'})
.forEach((e)=>{if(!myprops[e])this.scrollviewProps[e]=this.props[e]});
return {
keyboardSpace:0,
};
},
render(){
return (
<ScrollView ref='scrollView' {...this.scrollviewProps}>
{this.props.children}
<View style={{height:this.state.keyboardSpace}}></View>
</ScrollView>
);
},
inputFocused(_this,refName){
setTimeout(()=>{
let scrollResponder=this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(_this.refs[refName]),
this.props.offset, //additionalOffset
true
);
}, 50);
}
}) // KeyboardHandler
module.exports=KeyboardHandler;
First you need to install react-native-keyboardevents.
In XCode, in the project navigator, right click Libraries ➜ Add
Files to [your project's name] Go to node_modules ➜
react-native-keyboardevents and add the .xcodeproj file
In XCode, in the
project navigator, select your project. Add the lib*.a from the keyboardevents
project to your project's Build Phases ➜ Link Binary With Libraries Click
.xcodeproj file you added before in the project navigator and go the Build
Settings tab. Make sure 'All' is toggled on (instead of 'Basic').
Look for Header Search Paths and make sure it contains both
$(SRCROOT)/../react-native/React and $(SRCROOT)/../../React - mark
both as recursive.
Run your project (Cmd+R)
Then back in javascript land:
You need to import the react-native-keyboardevents.
var KeyboardEvents = require('react-native-keyboardevents');
var KeyboardEventEmitter = KeyboardEvents.Emitter;
Then in your view, add some state for the keyboard space and update from listening to the keyboard events.
getInitialState: function() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardDidShowEvent, (frames) => {
this.setState({keyboardSpace: frames.end.height});
});
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, (frames) => {
this.setState({keyboardSpace: 0});
});
return {
keyboardSpace: 0,
};
},
Finally, add a spacer to your render function beneath everything so when it increases size it bumps your stuff up.
<View style={{height: this.state.keyboardSpace}}></View>
It is also possible to use the animation api, but for simplicity's sake we just adjust after the animation.
react-native-keyboard-aware-scroll-view solved the problem for me.
react-native-keyboard-aware-scroll-view on GitHub
Try this:
import React, {
DeviceEventEmitter,
Dimensions
} from 'react-native';
...
getInitialState: function() {
return {
visibleHeight: Dimensions.get('window').height
}
},
...
componentDidMount: function() {
let self = this;
DeviceEventEmitter.addListener('keyboardWillShow', function(e: Event) {
self.keyboardWillShow(e);
});
DeviceEventEmitter.addListener('keyboardWillHide', function(e: Event) {
self.keyboardWillHide(e);
});
}
...
keyboardWillShow (e) {
let newSize = Dimensions.get('window').height - e.endCoordinates.height;
this.setState({visibleHeight: newSize});
},
keyboardWillHide (e) {
this.setState({visibleHeight: Dimensions.get('window').height});
},
...
render: function() {
return (<View style={{height: this.state.visibleHeight}}>your view code here...</View>);
}
...
It worked for me. The view basically shrinks when the keyboard is displayed, and grows back again when its hidden.
Just wanted to mention, now there is a KeyboardAvoidingView in RN. Just import it and use it as any other module in RN.
Here is the link to the commit on RN:
https://github.com/facebook/react-native/commit/8b78846a9501ef9c5ce9d1e18ee104bfae76af2e
It is available from 0.29.0
They have also included an example on UIExplorer.
Maybe is to late, but the best solution is to use a native library, IQKeyboardManager
Just drag and drop IQKeyboardManager directory from demo project to your iOS project. That's it. Also you can setup some valus, as isToolbar enabled, or the space between text input and keyboard in the AppDelegate.m file. More details about customisation are in the GitHub page link that I've added.
I used TextInput.onFocus and ScrollView.scrollTo.
...
<ScrollView ref="scrollView">
...
<TextInput onFocus={this.scrolldown}>
...
scrolldown: function(){
this.refs.scrollView.scrollTo(width*2/3);
},
#Stephen
If you don't mind not having the height animate at exactly the same rate that the keyboard appears, you can just use LayoutAnimation, so that at least the height doesn't jump into place. e.g.
import LayoutAnimation from react-native and add the following methods to your component.
getInitialState: function() {
return {keyboardSpace: 0};
},
updateKeyboardSpace: function(frames) {
LayoutAnimation.configureNext(animations.layout.spring);
this.setState({keyboardSpace: frames.end.height});
},
resetKeyboardSpace: function() {
LayoutAnimation.configureNext(animations.layout.spring);
this.setState({keyboardSpace: 0});
},
componentDidMount: function() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardDidShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
},
componentWillUnmount: function() {
KeyboardEventEmitter.off(KeyboardEvents.KeyboardDidShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.off(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
},
Some example animations are (I'm using the spring one above):
var animations = {
layout: {
spring: {
duration: 400,
create: {
duration: 300,
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: {
type: LayoutAnimation.Types.spring,
springDamping: 400,
},
},
easeInEaseOut: {
duration: 400,
create: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.scaleXY,
},
update: {
type: LayoutAnimation.Types.easeInEaseOut,
},
},
},
};
UPDATE:
See #sherlock's answer below, as of react-native 0.11 the keyboard resizing can be solved using built in functionality.
You can combine a few of the methods into something a little simpler.
Attach a onFocus listener on your inputs
<TextInput ref="password" secureTextEntry={true}
onFocus={this.scrolldown.bind(this,'password')}
/>
Our scroll down method looks something like :
scrolldown(ref) {
const self = this;
this.refs[ref].measure((ox, oy, width, height, px, py) => {
self.refs.scrollView.scrollTo({y: oy - 200});
});
}
This tells our scroll view (remember to add a ref) to scroll to down to the position of our focused input - 200 (it's roughly the size of the keyboard)
componentWillMount() {
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardWillHide',
this.keyboardDidHide.bind(this)
)
}
componentWillUnmount() {
this.keyboardDidHideListener.remove()
}
keyboardDidHide(e) {
this.refs.scrollView.scrollTo({y: 0});
}
Here we reset our scroll view back to the top,
I'm using a simpler method, but it's not animated yet. I have a component state called "bumpedUp" which I default to 0, but set to 1 when the textInput gets focus, like this:
On my textInput:
onFocus={() => this.setState({bumpedUp: 1})}
onEndEditing={() => this.setState({bumpedUp: 0})}
I also have style that gives the wrapping container of everything on that screen a bottom margin and negative top margin, like this:
mythingscontainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
},
bumpedcontainer: {
marginBottom: 210,
marginTop: -210,
},
And then on the wrapping container, I set the styles like this:
<View style={[styles.mythingscontainer, this.state.bumpedUp && styles.bumpedcontainer]}>
So, when the "bumpedUp" state gets set to 1, the bumpedcontainer style kicks in and moves the content up.
Kinda hacky and the margins are hardcoded, but it works :)
I use brysgo answer to raise the bottom of my scrollview. Then I use the onScroll to update the current position of the scrollview. I then found this React Native: Getting the position of an element to get the position of the textinput. I then do some simple math to figure out if the input is in the current view. Then I use scrollTo to move the minimum amount plus a margin. It's pretty smooth. Heres the code for the scrolling portion:
focusOn: function(target) {
return () => {
var handle = React.findNodeHandle(this.refs[target]);
UIManager.measureLayoutRelativeToParent( handle,
(e) => {console.error(e)},
(x,y,w,h) => {
var offs = this.scrollPosition + 250;
var subHeaderHeight = (Sizes.width > 320) ? Sizes.height * 0.067 : Sizes.height * 0.077;
var headerHeight = Sizes.height / 9;
var largeSpace = (Sizes.height - (subHeaderHeight + headerHeight));
var shortSpace = largeSpace - this.keyboardOffset;
if(y+h >= this.scrollPosition + shortSpace) {
this.refs.sv.scrollTo(y+h - shortSpace + 20);
}
if(y < this.scrollPosition) this.refs.sv.scrollTo(this.scrollPosition - (this.scrollPosition-y) - 20 );
}
);
};
},
I also meet this question. Finally, I resolve it by defining the height of each scene, such as:
<Navigator
...
sceneStyle={{height: **}}
/>
And, I also use a third-party module https://github.com/jaysoo/react-native-extra-dimensions-android to get the real height.

Categories

Resources