I'm creating a React Native checkbox/switch component (similar to a generic iOS switch).
The animation and functionality is working as required, but I'm having an issue with the initial view state.
When rendering the component, it's set in the "off" state initially. I can set an explicit left value to resolve this (e.g setting a dynamic left value based on the state of checked), but that will remove the Animated effect that's applied when the checkbox is changed.
Is there a way to update the checkbox with an initial state (true/false) without affecting the animation?
The component is below. It received two props presently (checked = a bool, handleChange = function to change the status of checked from the parent component).
const CheckboxToggle = ({ checked, handleChange }) => {
const xAnimation = useRef(new Animated.Value(0)).current;
const startThumbAnimation = () => {
Animated.timing(xAnimation, {
toValue: checked ? 0 : 50,
duration: 300,
useNativeDriver: false,
}).start();
};
const animatedThumbStyles = {
transform: [
{
translateX: xAnimation,
}
]
}
return (
<TouchableWithoutFeedback
onPress={() => {
handleChange();
startThumbAnimation();
}}
>
<View>
<Track />
<AnimatedThumb
checked={checked}
style={animatedThumbStyles}
>
{
checked
? <CheckboxIconTrue source={ic_switch_on} />
: <CheckboxIconFalse source={ic_switch_off} />
}
</AnimatedThumb>
</View>
</TouchableWithoutFeedback>
)
}
export default CheckboxToggle;
You can implement this way:
const CheckboxToggle = ({ defaultCheck, checked, handleChange }) => {
//using defaultCheck to conditionally set the value.
const xAnimation = useRef(new Animated.Value(defaultCheck ? 50 : 0)).current;
const startThumbAnimation = () => {
Animated.timing(xAnimation, {
toValue: checked ? 0 : 50,
duration: 300,
useNativeDriver: false,
}).start();
};
const animatedThumbStyles = {
transform: [
{
translateX: xAnimation,
}
]
}
return (
<TouchableWithoutFeedback
onPress={() => {
handleChange();
startThumbAnimation();
}}
>
<View>
<Track />
<AnimatedThumb
checked={checked}
style={animatedThumbStyles}
>
{
checked
? <CheckboxIconTrue source={ic_switch_on} />
: <CheckboxIconFalse source={ic_switch_off} />
}
</AnimatedThumb>
</View>
</TouchableWithoutFeedback>
)
}
export default CheckboxToggle;
I would like to point out that you are using useNativeDriver = false, this may lead to slow animations.
Also, React-Native has a Switch Component. Why don't you use that?
https://reactnative.dev/docs/switch
Related
I am using react-spring for animation and all the animations start once the page is loaded. I want to control the start of the animation. The desired outcome is to let the components down in the screen start the animation once they are in view (i.e the user scrolled down). The code follows something like this :
const cols = [
/*Components here that will be animated ..*/
{component: <div><p>A<p></div> , key:1},
{component: <div><p>B<p></div> , key:2},
{component: <div><p>C<p></div> , key:3},
]
export default function foocomponent(){
const [items, setItems] = React.useState(cols);
const [appear, setAppear] = React.useState(false); // Should trigger when the component is in view
const transitions = useTransition(items, (item) => item.key, {
from: { opacity: 0, transform: 'translateY(70px) scale(0.5)', borderRadius: '0px' },
enter: { opacity: 1, transform: 'translateY(0px) scale(1)', borderRadius: '20px', border: '1px solid #00b8d8' },
// leave: { opacity: 1, },
delay: 200,
config: config.molasses,
})
React.useEffect(() => {
if (items.length === 0) {
setTimeout(() => {
setItems(cols)
}, 2000)
}
}, [cols]);
return (
<Container>
<Row>
{appear && transitions.map(({ item, props, key }) => (
<Col className="feature-item">
<animated.div key={key} style={props} >
{item.component}
</animated.div>
</Col>
))}
</Row>
</Container>
);
}
I tried using appear && transitions.map(...) but unfortunately that doesn't work. Any idea how should I control the start of the animation based on a condition?
I use https://github.com/civiccc/react-waypoint for this type of problems.
If you place this hidden component just before your animation. You can switch the appear state with it. Something like this:
<Waypoint
onEnter={() => setAppear(true) }
/>
You can even specify an offset with it. To finetune the experience.
If you wish to have various sections fade in, scroll in, whatever on enter, it's actually very simple to create a custom wrapper. Since this question is regarding React Spring, here's an example but you could also refactor this a little to use pure CSS.
// React
import { useState } from "react";
// Libs
import { Waypoint } from "react-waypoint";
import { useSpring, animated } from "react-spring";
const FadeIn = ({ children }) => {
const [inView, setInview] = useState(false);
const transition = useSpring({
delay: 500,
to: {
y: !inView ? 24 : 0,
opacity: !inView ? 0 : 1,
},
});
return (
<Waypoint onEnter={() => setInview(true)}>
<animated.div style={transition}>
{children}
</animated.div>
</Waypoint>
);
};
export default FadeIn;
You can then wrap any component you want to fade in on view in this FadeIn component as such:
<FadeIn>
<Clients />
</FadeIn>
Or write your own html:
<FadeIn>
<div>
<h1>I will fade in on enter</h1>
</div>
</FadeIn>
I am trying to conditionally render part of an object (user comment) onClick of button.
The objects are being pulled from a Firebase Database.
I have multiple objects and want to only render comments for the Result component I click on.
The user comment is stored in the same object as all the other information such as name, date and ratings.
My original approach was to set a boolean value of false to each Result component and try to change this value to false but cannot seem to get it working.
Code and images attached below, any help would be greatly appreciated.
{
accumRating: 3.7
adheranceRating: 4
cleanRating: 2
date: "2020-10-10"
place: "PYGMALIAN"
staffRating: 5
timestamp: t {seconds: 1603315308, nanoseconds: 772000000}
userComment: "Bad"
viewComment: false
}
const results = props.data.map((item, index) => {
return (
<div className='Results' key={index}>
<span>{item.place}</span>
<span>{item.date}</span>
<Rating
name={'read-only'}
value={item.accumRating}
style={{
width: 'auto',
alignItems: 'center',
}}
/>
<button>i</button>
{/* <span>{item.userComment}</span> */}
</div >
)
})
You have to track individual state of each button toggle in that case.
The solution I think of is not the best but you could create a click handler for the button and adding a classname for the span then check if that class exists. If it exists then, just hide the comment.
Just make sure that the next sibling of the button is the target you want to hide/show
const toggleComment = (e) => {
const sibling = e.target.nextElementSibling;
sibling.classList.toggle('is-visible');
if (sibling.classList.contains('is-visible')) {
sibling.style.display = 'none'; // or set visibility to hidden
} else {
sibling.style.display = 'inline-block'; // or set visibility to visible
}
}
<button onClick={toggleComment}>i</button>
<span>{item.userComment}</span>
You can try like this:
const [backendData, setBackendData] = useState([]);
...
const showCommentsHandler = (viewComment, index) => {
let clonedBackendData = [...this.state.backendData];
clonedBackendData[index].viewComment = !viewComment;
setBackendData(clonedBackendData);
}
....
return(
<div>
....
<button onClick={() => showCommentsHandler(item.viewComment, index)}>i</button>
{item.viewComment && item.userComment}
<div>
You can store an array with that places which are clicked, for example:
const [ selectedItems, setSelectedItems] = React.useState([]);
const onClick = (el) => {
if (selectedItems.includes(el.place)) {
setSelectedItems(selectedItems.filter(e => e.place !== el.place));
} else {
setSelectedItems(selectedItems.concat(el));
}
}
and in your render function
const results = props.data.map((item, index) => {
return (
<div className='Results' key={index}>
<span>{item.place}</span>
<span>{item.date}</span>
<Rating
name={'read-only'}
value={item.accumRating}
style={{
width: 'auto',
alignItems: 'center',
}}
/>
<button onClick={() => onClick(item)}>i</button>
{ /* HERE */ }
{ selectedItems.includes(item.place) && <span>{item.userComment}</span> }
</div >
)
})
You need to use useState or your component won't update even if you change the property from false to true.
In order to do so you need an id since you might have more than one post.
(Actually you have a timestamp already, you can use that instead of an id.)
const [posts, setPosts] = useState([
{
id: 1,
accumRating: 3.7,
adheranceRating: 4,
cleanRating: 2,
date: "2020-10-10",
place: "PYGMALIAN",
staffRating: 5,
timestamp: { seconds: 1603315308, nanoseconds: 772000000 },
userComment: "Bad",
viewComment: false
}
]);
Create a function that updates the single property and then updates the state.
const handleClick = (id) => {
const singlePost = posts.findIndex((post) => post.id === id);
const newPosts = [...posts];
newPosts[singlePost] = {
...newPosts[singlePost],
viewComment: !newPosts[singlePost].viewComment
};
setPosts(newPosts);
};
Then you can conditionally render the comment.
return (
<div className="Results" key={index}>
<span>{item.place}</span>
<span>{item.date}</span>
<Rating
name={"read-only"}
value={item.accumRating}
style={{
width: "auto",
alignItems: "center"
}}
/>
<button onClick={() => handleClick(item.id)}>i</button>
{item.viewComment && <span>{item.userComment}</span>}
</div>
);
Check this codesandbox to see how it works.
I'm trying to play a gsap animation on component did mount in a Gatsby site but my refs aren't being applied.
const PricingList = ({ classes }) => {
let pricingCard = useRef([]);
useEffect(() => {
console.log('start Animation', pricingCard.current);
TweenMax.staggerFrom(pricingCard.current, 0.4, { opacity: 0, y: 100 }, 0.5);
}, []);
return (
<StaticQuery
query={graphql`
{
Prices: contentfulConfig {
pricing {
priceBand {
title
price
}
priceBand2 {
price
title
}
priceBand3 {
price
title
}
}
}
}
`}
render={(data) => (
<Fragment>
<div className={classes.Container}>
<PricingItem
ref={(el) => {
pricingCard.current[0] = el;
}}
/>
<PricingItem
ref={(el) => {
pricingCard.current[1] = el;
}}
/>
<PricingItem
ref={(el) => {
pricingCard.current[2] = el;
}}
/>
</div>
</Fragment>
)}
/>
);
};
I have tried -
pricingCard.current.push(el);
without any luck, I just get an empty array in console.
I have also tried -
useEffect(() => {
console.log('start Animation', pricingCard.current);
TweenMax.staggerFrom(pricingCard.current, 0.4, { opacity: 0, y: 100 }, 0.5);
}, [pricingCard]);
Thinking it might need to wait to be updated after the component mounted, but no luck.
Any help would be appreciated.
Thanks in advance.
For animation you might want to use useLayoutEffect instead of useEffect.
Is it going to be always 3 PricingItems? In this case you can create 3 separate refs for each (const pricingItem1 = useRef(null)) and in render <PricingItem ref={pricingItem1} />.
Also can you confirm that the function from the render prop has been called?
This might refer to other relevant general questions like how to update a child component from the parent, though I'd like to hear any fair judgement of my design solution to the following scenario.
I have a parent class where I store css attributes for 2 children objects.
import React from 'react'
import Item from './item/Item'
class Small_gallery extends React.Component {
constructor(props) {
super(props);
this.state = {
chosenVal: 0,
};
this.listObjParams = [
// Style 1
{
left: 300,
zIndex: 0
},
//Style 2
{
left: 320,
zIndex: 1
}
];
this.handleClick = this.handleClick.bind(this);
this.calculateShift = this.applyNewStyle.bind(this);
this.listItems = this.listObjParams.map((objStyle, i) =>
<Item
key={i}
id={i}
objStyle={objStyle}
onClick={this.handleClick}
/>
);
}
handleClick = (indexFromChild) => {
this.setState({chosenVal: indexFromChild});
this.applyNewStyle(indexFromChild)
};
applyNewStyle = (clickedIndex) => {
if (clickedIndex === 0) {
// somehow I want to apply new css style 2 to the clicked? <Item> child
};
render() {
return (
<div>
{this.listItems}
</div>
)
}
Child component is rather trivial:
class Item extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div
onClick={(e) => {
e.preventDefault();
this.props.onClick(this.props.id)
}}
style={{
left: this.props.objStyle.left,
zIndex: this.props.objStyle.zIndex
}}
>
</div>
);
}
}
The question is: how can I apply style 1 or 2 to the clicked Item component(depending on the index I am returning)? I've read about getDerivedStateFromProps instead of using deprecated componentWillReceiveProps here https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607 but it's not a solution for me.
I expect number of created Items to grow in the future to 10-20, so it makes no sense to populate state of Item with this.listObjParams when creating it, or am I wrong here?
I have a working example below, so to cover what I did:
Create a prop that takes an array of items, more items more looped <Item />'s will appear.
Styles are either activeStyles || inactiveStyles it is based on the currentId matching the id from object (from array prop = items).
import React from "react";
const inactiveStyles = {
left: 300,
zIndex: 0,
backgroundColor: "#E9573F"
};
const activeStyles = {
left: 320,
zIndex: 1,
backgroundColor: "#00B1E1"
};
const inboundItems = [
{
id: 0
},
{
id: 1
},
{
id: 2
}
];
// Note - added to show it working not needed
const defaultStyles = {
display: "block",
border: "1px solid black",
width: 50,
height: 50
};
export const Item = ({ id, onClick, style }) => (
<>
<pre>{JSON.stringify({ styles: style }, null, 2)}</pre>
<div
{...{ id }}
style={{ ...defaultStyles, ...style }}
onClick={e => {
e.preventDefault();
onClick(id);
}}
/>
</>
);
export const SmallGallery = ({ items = inboundItems }) => {
const [currentId, setCurrentId] = React.useState(null);
const getStyles = selectedId => {
return currentId === selectedId ? activeStyles : inactiveStyles;
};
return items.map(({ id, ...item }) => (
<Item
key={id}
{...{ id }}
{...item}
style={getStyles(id)}
onClick={selectedId => setCurrentId(selectedId)}
/>
));
};
export default SmallGallery;
Let me know what you think, I added a screenshot to show styles being added.
For <Item/> you can use simple functional component. Optimal for simple, not so complex use cases.
E.g
const Item = ({ id, clickHandler, objStyle }) => (
<div
onClick={e => {
e.preventDefault();
clickHandler(id);
}}
style={...objStyle}
/>
);
PureComponent will be updated on props change, too.
In full class component you can use shouldComponentUpdate() to force rerendering on props change. No need to duplicate data (into state) using getDerivedStateFromProps (depends on use case).
Search for some tutorials (f.e. typical todo examples) since you have no idea about state management, updating etc.
Placing listObjParams outside of state won't force rerendering on update. BTW it looks more like a style pool - maybe you should have a child params array... you can combine it with style index array or keep them (and pass as props) separately.
constructor(props) {
super(props);
this.state = {
// chosenVal: 0, // temporary handler param? probably no need to store in the state
listObjStyles: [0, 1] // style indexes
};
this.stylePool = [
// Style 1
{
left: 300,
zIndex: 0
},
//Style 2
{
left: 320,
zIndex: 1
}
];
usage:
this.listItems = this.state.listObjStyles.map((styleIndex, i) => <Item
key={i}
id={i}
objStyle={this.stylePool[ styleIndex ]}
clickHandler={this.handleClick}
/>
Updating listObjStyles (setState()) will force rerendering, updating this.stylePool won't (move to the state if rerendering required).
Of course stylePool can contain more than 2 styles for different item 'states'. You can make styles for selected, liked, unliked - by storing indexes in an array you can mix any of them with custom logic (f.e. only one selected, many liked).
10-20 items is not the case where you need special optimizations (other than avoiding unnecessary rerenderings).
Just to sum up what I've done to make it all work based on two answers (still a rather toy example):
Parent:
import Item from './item/Item'
class Small_gallery extends React.Component {
constructor(props) {
super(props);
this.state = {
listObjStyles: [0, 1]
};
this.stylePool = [
{
position: 'absolute',
width: 600,
left: 300,
height: 100,
backgroundColor: '#000',
zIndex: 0,
transition: 'all 1s ease'
},
{
position: 'absolute',
width: 600,
left: 720,
height: 350,
backgroundColor: '#ccc',
zIndex: 1,
transition: 'all 2s ease'
}]
}
handleClick = (indexFromChild) => {
console.log(indexFromChild)
if (indexFromChild === 0) {
this.setState({
listObjStyles: [1, 0]
})
} else if (indexFromChild === 1) {
this.setState({
listObjStyles: [0, 1]
})
}
}
render() {
return (
<>
<div style={{display: 'flex', margin: 40}}>
{this.state.listObjStyles.map((styleIndex, i) =>
<Item
key={i}
id={i}
objStyle={this.stylePool[styleIndex]}
onClick={this.handleClick}
/>
)}
</div>
</>)
}
}
Child:
const Item = ({id, onClick, objStyle}) => (
<div
onClick={e => {
e.preventDefault();
onClick(id)
}}
style={{...objStyle}}
/>
);
export default Item
I'm displaying an array of items (Circle components) in my view,
but I'm not sure how to hide all the others when I click one (onPress is set up to zoom in and give more info cards about that one Circle I click).
Here is my RN code .. any ideas?
class Circle extends Component {
constructor(props) {
super(props);
this.state = { opened: false};
this.onPress = this.onPress.bind(this);
}
onPress() {
this.props.onPress();
if (this.props.noAnimation) {
return;
}
if (this.state.opened) {
this.refs.nextEpisode.fadeOutLeft();
this.refs.description.fadeOutDownBig();
return this.setState({opened: false, windowPos: null});
}
this.refs.container.measureInWindow((x, y) => {
this.refs.nextEpisode.slideInLeft();
setTimeout(() => this.refs.description.fadeInUpBig(), 400);
this.setState({
opened: true,
windowPos: { x, y },
});
});
}
render() {
const data = this.props.data;
const { opened } = this.state;
const styles2 = getStyles(opened, (this.props.index % 2 === 0));
const containerPos = this.state.windowPos ? {
top: - this.state.windowPos.y + 64
} : {};
return (
<TouchableWithoutFeedback onPress={this.onPress}>
<View style={[styles2.container, containerPos]} ref="container" >
<TvShowImage tvShow={data} style={styles2.image} noShadow={opened} openStatus={opened}/>
<View style={styles2.title}>
<Title
tvShow={data}
onPress={this.onPress}
noShadow={opened}
/>
<Animatable.View
style={styles2.animatableNextEpisode}
duration={800}
ref="nextEpisode"
>
<NextEpisode tvShow={data}/>
</Animatable.View>
</View>
<Animatable.View
style={styles2.description}
duration={800}
ref="description"
delay={400}
>
<Text style={styles2.descriptionText}>{data.item_description}</Text>
</Animatable.View>
</View>
</TouchableWithoutFeedback>
);
}
}
Circle.defaultProps = {
index: 0,
onPress: () => {}
};
(Please ignore that some of variable names are tv-show related when the photos are food-related, haven't had time to fix yet).
FYI the parent component that maps the array of Circle components looks like this:
class Favorites extends React.Component {
constructor(props) {
super(props);
this.state = {
circleCount: 0
};
this.addCircle = this.addCircle.bind(this);
}
componentDidMount() {
for(let i = 0; i < this.props.screenProps.appstate.length; i++) {
setTimeout(() => {
this.addCircle();
}, (i*100));
}
}
addCircle = () => {
this.setState((prevState) => ({circleCount: prevState.circleCount + 1}));
}
render() {
var favoritesList = this.props.screenProps.appstate;
var circles = [];
for (let i = 0; i < this.state.circleCount; i++) {
circles.push(
<Circle key={favoritesList[i].url} style={styles.testcontainer} data={favoritesList[i]}>
</Circle>
);
}
return (
<ScrollView style={{backgroundColor: '#fff9f9'}}>
<View style={styles.favoritesMainView}>
<View style={styles.circleContainer}>
{circles}
</View>
</View>
</ScrollView>
);
}
}
Off the top of my head (if I'm understanding what you want) there could be few solutions.
You may need to track the "selected" circle and style the components based on that. For instance you could style the ones not selected by using {height: 0} or {opacity: 0} if you still need the height of the elements.
To track I would try the following:
In Favorites state:
this.state = {
circleCount: 0,
selected: -1
};
And pass 3 new values to circle, the third is function to change the state of "selected":
<Circle
key={favoritesList[i].url}
style={styles.testcontainer}
data={favoritesList[i]}
index={i}
selected={this.state.selected}
onClick={(index) => {
this.setState(prevState => {
return { ...prevState, selected: index }
});
}}
/>
In Circle we use pass the index that was pressed back up to Favorites using the method we passed down:
onPress() {
this.props.onClick(this.props.index);
...
In Circle's render method we create an opacity style to hide any elements not currently selected (but only if there is one selected - meaning that if it is -1 then none are selected and no opacity should be applied to any Circle:
render() {
const { selected, index } = this.props;
let opacityStyle = {};
if(selected !== -1) {
if(selected !== index) {
opacityStyle = { opacity: 0 }
}
}
Last step is to apply the style (either an empty object, or opacity: 0):
<TouchableWithoutFeedback onPress={this.onPress}>
<View style={[styles2.container, containerPos, opacityStyle]} ref="container" >
I am not sure where you are closing or zooming out. Just when you close or zoom out of a circle you just need to call this.props.onClick(-1) to effectively deselect the circle. This will mean no other circles will have the opacity applied.
One thing you may need to do to ensure "selected" is not removed, is change your setState() method in Favorites:
addCircle = () => {
this.setState(prevState => {
return { ...prevState, circleCount: prevState.circleCount + 1 };
}
)}
In this version we are only changing circleCount and leaving any other properties that prevState has - in this case "selected" remains unchanged.