I'm new to React and I'm trying to make a simple animation, but when the animation ends there is literally a split second that is showing the old values of opacitate & translate.Is there a way that i can make that dissapper?
I've tried to use useRef and re-render the component but no luck.Ignore the timeout functionz
const { useEffect, useState } = React;
const Titlu = () => {
let [opacitate, setOpacitate] = useState(0);
let [translate, setTranslate] = useState(-30);
function Schimba() {
setOpacitate(prevOpacity => prevOpacity = 1);
setTranslate(prevTranslate => prevTranslate = 20);
}
function timeout(timp) {
return new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
})
}
return (
<div className="Part1">
<h1 className="ForkyTitlu"
onAnimationEnd={Schimba}
style={{
opacity:opacitate,
transform: `translate(${translate}%, 0%)`
}} >
<span className ="Forky">Forky</span>
<span className ="Nutrition">Nutrition</span>
</h1>
</div>
);
}
ReactDOM
.createRoot(root)
.render(<Titlu />);
.Part1 {
display: inline-flex;
margin-bottom: 50vh;
border-bottom: 3px black;
}
.ForkyTitlu {
color: orange;
font-size: 3vw;
/*
margin-left: 12vw;
margin-top: 40vh;
transform: translateX(-50%);
*/
animation-name: titluAnimation;
animation-delay: 1s;
animation-duration: 2s;
animation-iteration-count: 1;
position: relative;
}
#keyframes titluAnimation {
100% {
opacity: 1;
transform: translateX(20%);
}
}
.Forky {
color: black;
font-size: 9vw;
text-shadow: -30px 15px 30px #0000009c;
}
.Nutrition {
color: orange;
font-size: 3.5vw;
text-shadow: -30px 15px 30px orange;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="root"></div>
When onAnimationEnd calls Schimba, the animation is over, and the CSS values are resettled top their original values. This is the gap you're seeing.
However, you don't really need a state. Move all animation related properties, including the initial state to the animation:
#keyframes titluAnimation {
from {
opacity: 0;
transform: translateX(-30%);
}
to {
opacity: 1;
transform: translateX(20%);
}
}
And define the animation-fill-mode (I've used the animation shorthand) to be forwards:
animation: titluAnimation 2s forwards;
forwards
The target will retain the computed values set by the last keyframe encountered during execution.
const Titlu = () => (
<div className = "Part1">
<h1 className = "ForkyTitlu">
<span className ="Forky">Forky</span>
<span className ="Nutrition">Nutrition</span>
</h1>
</div>
);
ReactDOM
.createRoot(root)
.render(<Titlu />);
.Part1 {
display: inline-flex;
margin-bottom: 50vh;
border-bottom: 3px black;
}
.ForkyTitlu {
color: orange;
font-size: 3vw;
animation: titluAnimation 2s forwards;
position: relative;
}
#keyframes titluAnimation {
from {
opacity: 0;
transform: translateX(-30%);
}
to {
opacity: 1;
transform: translateX(20%);
}
}
.Forky {
color: black;
font-size: 9vw;
text-shadow: -30px 15px 30px #0000009c;
}
.Nutrition {
color: orange;
font-size: 3.5vw;
text-shadow: -30px 15px 30px orange;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="root"></div>
If you want/need to use state to control the animation, it's better to define the start/end states as classes, toggle them with the state, and use CSS transition to animate the change.
Example - click the Toggle button to see the animation:
const { useState } = React;
const Titlu = () => {
const [start, setState] = useState(true);
const toggleStart = () => setState(s => !s);
return (
<div>
<div className = "Part1">
<h1 className = {`ForkyTitlu ${start ? 'start' : 'end'}`}>
<span className ="Forky">Forky</span>
<span className ="Nutrition">Nutrition</span>
</h1>
</div>
<button onClick={toggleStart}>Toggle</button>
</div>
);
};
ReactDOM
.createRoot(root)
.render(<Titlu />);
.Part1 {
display: flex;
border-bottom: 3px black;
}
.ForkyTitlu {
color: orange;
font-size: 3vw;
position: relative;
transition: all 2s;
}
.ForkyTitlu.start {
opacity: 0;
transform: translateX(-30%);
}
.ForkyTitlu.end {
opacity: 1;
transform: translateX(20%);
}
.Forky {
color: black;
font-size: 9vw;
text-shadow: -30px 15px 30px #0000009c;
}
.Nutrition {
color: orange;
font-size: 3.5vw;
text-shadow: -30px 15px 30px orange;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="root"></div>
Related
I've successfully mapped over text and have styled it with transition effects when going from one slide to the next as you can see here:
Following a similar concept with buttons isn't working. There should only be one button active per slide like you see here:
I want the buttons to have the same effect as the text, but I'm getting behaviors like you see here:
As you can see, there is no transition effect on the button when clicking to the second slide, and it also appears in a lower spot.
And lastly, when resizing the window, buttons are overlapping like you see here:
Don't know what to try next.
Here's the ImageSlider component:
import { useState } from "react";
import { SliderData } from "../data";
import { categories } from "../data";
import ShopNowButtonActive from "./ShopNowButtonActive";
import { IoIosArrowBack } from "react-icons/io";
import { IoIosArrowForward } from "react-icons/io";
import "./ImageSlider.css";
import ShopNowButton from "./ShopNowButton";
const ImageSlider = ({ slides }) => {
const [current, setCurrent] = useState(0);
const length = slides.length;
const nextSlide = () => {
setCurrent(current === length - 1 ? 0 : current + 1);
};
const prevSlide = () => {
setCurrent(current === 0 ? length - 1 : current - 1);
};
return (
<div className="slider">
<IoIosArrowBack className="left-arrow" onClick={prevSlide} />
{SliderData.map((slide, index) => (
<div key={slide.id}>
<img
src={slide.img}
alt=""
className={index === current ? "slide active" : "slide"}
/>
<div className="info-container">
<div className={index === current ? "title active" : "title"}>
{slide.title}
</div>
<div className={index === current ? "desc active" : "desc"}>
{slide.desc}
</div>
{categories.map((item, index) =>
index === current ? (
<ShopNowButtonActive item={item} />
) : (
<ShopNowButton item={item} />
)
)}
</div>
</div>
))}
<IoIosArrowForward className="right-arrow" onClick={nextSlide} />
</div>
);
};
export default ImageSlider;
The css file:
.slider {
height: 90vh;
margin-bottom: 0.5rem;
}
.left-arrow {
position: absolute;
top: 45%;
left: 32px;
font-size: 2rem;
cursor: pointer;
opacity: 0.5;
z-index: 1;
}
.slide.active {
opacity: 1;
width: 100%;
height: 88%;
object-fit: cover;
object-position: center;
-webkit-clip-path: polygon(100% 0, 100% 80%, 50% 100%, 0 80%, 0% 0%);
clip-path: polygon(100% 0, 100% 80%, 50% 100%, 0 80%, 0% 0%);
}
.slide {
opacity: 0;
transition: 500ms opacity ease-in-out;
width: 100%;
height: 88%;
object-fit: cover;
object-position: center;
position: absolute;
-webkit-clip-path: polygon(100% 0, 100% 80%, 50% 100%, 0 80%, 0% 0%);
clip-path: polygon(100% 0, 100% 80%, 50% 100%, 0 80%, 0% 0%);
}
.info-container {
display: flex;
flex-direction: column;
width: 40%;
height: 100%;
position: absolute;
top: 45%;
right: 30px;
}
.title.active {
opacity: 1;
transition-delay: 700ms;
font-size: 4rem;
}
.title {
opacity: 0;
transition: 200ms opacity ease-in-out;
font-size: 4rem;
}
.desc.active {
opacity: 1;
padding-top: 1.5em;
transition-delay: 700ms;
font-size: 1.25rem;
font-weight: 500;
letter-spacing: 3px;
}
.desc {
opacity: 0;
padding-top: 1.5em;
transition: 200ms opacity ease-in-out;
font-size: 1.25rem;
font-weight: 500;
letter-spacing: 3px;
}
.right-arrow {
position: absolute;
top: 45%;
right: 32px;
font-size: 2rem;
cursor: pointer;
opacity: 0.5;
z-index: 1;
}
The ShopNowButtonActive component:
import React from "react";
import styled from "styled-components/macro";
import { Link } from "react-router-dom";
const ButtonActive = styled.button`
opacity: 1;
padding: 0.5rem;
margin-top: 2.5rem;
width: 8rem;
font-size: 20px;
background-color: transparent;
cursor: pointer;
transition-delay: 700ms;
`;
const ShopNowButtonActive = ({ item }) => {
return (
<Link to={`/products/${item.cat}`}>
<ButtonActive>SHOP NOW</ButtonActive>
</Link>
);
};
export default ShopNowButtonActive;
And finally, the ShopNowButton component:
import React from "react";
import styled from "styled-components/macro";
import { Link } from "react-router-dom";
const Button = styled.button`
opacity: 0;
/* display: none; */
padding: 0.5rem;
margin-top: 2.5rem;
width: 8rem;
font-size: 20px;
background-color: transparent;
cursor: pointer;
transition: 200ms opacity ease-in-out;
`;
const ShopNowButton = ({ item }) => {
return (
<Link to={`/products/${item.cat}`}>
<Button>SHOP NOW</Button>
</Link>
);
};
export default ShopNowButton;
(Sorry for the use of both an external css file and styled components.)
Any suggestions?
I have recreated the above scenario using some static data. I have modified some of the css. It is working as expected. I also observed that the only major difference between ShopNowButton and ShopNowButtonActive was opacity property which hides the element. The reason you are observing 2 buttons because they were all there in the dom actually.(They were not hiding properly due to which we are observing more shop now buttons and every time we click on next icon the corresponding button is being displayed. Basically all the buttons are there on the page itself.)
Please find the sandbox url below.
https://codesandbox.io/s/stackoverflow-6u05e7?file=/src/ImageSlider/ImageSlider.js
hi this is my code and i want to change my Navigation bar color on scrolling but how can i do it?
i want to remove my class and add my new class to it,but i cant do this and i am newbie in react.
do i need life cycle hooks?
what should i do for my state?
import React from 'react';
import DrawerToggleButton from '../SideDrawer/DrawerToggleButton'
import './Toolbar.css'
class Toolbar extends React.Component {
state = {
};
scroll = () => {
if (this.scrollTop() <= 10){
(".toolbar").addClass("scroll");
}
else{
(".toolbar").removeClass("scroll")
}
};
render() {
return(
<header className="toolbar">
<nav className="toolbar__navigation">
<div className="toolbar__toggle-button">
<DrawerToggleButton click={this.props.drawerClickHandler} />
</div>
<div className="toolbar__logo"><a href={"/"}>THE LOGO</a></div>
<div className="spacer"/>
<div className="toolbar_navigation-items">
<ul>
<li><a href={"/"}>Products</a> </li>
<li><a href={"/"}>Users</a> </li>
</ul>
</div>
</nav>
</header>
);
}
}
export default Toolbar;
and this is my css code:
.toolbar {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: linear-gradient(
to right,
#e4faff 0%,
#e9f8ff 50%,
#f9f6ff 50%,
#e9f8ff 100%);
height: 56px;
z-index: 200;
}
.toolbar__navigation {
display: flex;
height: 100%;
align-items: center;
padding: 0 1rem;
}
.toolbar__logo {
margin-left: 1rem;
}
.toolbar__logo a {
color: #3500b6;
text-decoration: none;
font-size: 1.5rem;
}
.spacer {
flex: 1;
}
.toolbar_navigation-items ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
}
.toolbar_navigation-items li {
padding: 0 0.5rem;
}
.toolbar_navigation-items a {
color: #370ab6;
text-decoration: none;
font-size: 18px;
font-weight: bold;
}
.toolbar_navigation-items a:hover,
.toolbar_navigation-items a:active {
color: #000000;
border-bottom: 2px solid black;
}
.toolbar.scroll {
background-color: black;
color: white;
}
#media (max-width: 768px) {
.toolbar_navigation-items {
display: none;
}
}
#media (min-width: 769px) {
.toolbar__toggle-button {
display: none;
}
.toolbar__logo {
margin-left: 0;
}
}
<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>
i used javascript as i now about this syntax but in react what should i do?
I'm currently trying to create an animation on an H2, using the pseudos ::before and after. But the ::before and ::after are not showing in my HTML.
What am I doing wrong here? Looking at styled components docs this should just work. I'm aware of the weird animation function. But this does not have any influence in the before after. I already completely removed it but it still doesn't render.
import React from 'react'
import styled, { keyframes, css } from 'styled-components'
import PropTypes from 'prop-types'
const Wrapper = styled.h2`
position: relative;
font-size: 1.5rem;
color: #ffffff;
font-weight: 600;
text-align: center;
text-transform: uppercase;
letter-spacing: 0.01em;
transform: scale3d(1,1,1);
opacity: 1;
&::before, &::after{
content: ${(props) => props.text};
position: absolute;
top: 0;
left: 0;
right: 0;
overflow: hidden;
background: #333333;
color: #ffffff;
clip: rect(0, 900px, 0, 0);
}
&::before {
left: 7px;
text-shadow: 1px 0 green;
animation: ${glitchEffect} 3s infinite linear alternate-reverse;
}
&::after {
left: 3px;
text-shadow: -1px 0 red;
animation: ${glitchEffect} 2s infinite linear alternate-reverse;
}
`
const glitchEffect = keyframes`
${setInterval(createAnimation, 200)}
`
function createAnimation(){
const single = `clip: rect(${(Math.floor(Math.random() * 100 + 1))}px, 9999px, ${(Math.floor(Math.random() * 100 + 1))}px, 0);`
return css`${single}`
}
export default function Glitch({ text }){
return (
<Wrapper text={text}>{text}</Wrapper>
)
}
Glitch.propTypes = {
text: PropTypes.string.isRequired
}
A few things:
content: ${(props) => props.text}; wouldn't work, you need to add double quotes around the text like so content: "${(props) => props.text}";
The second issue is setInterval(createAnimation, 200). This will return an integer (a handle to the interval that you've just created). This will be needed to clear the interval once you're done with the animation for example.
If what you want to do is to generate a some keyframes, then you need to call createAnimation manually like so
import React from "react";
import styled, { keyframes, css } from "styled-components";
const glitchEffect = keyframes`
from {
${createAnimation()}
}
to {
${createAnimation()}
}
`;
const Wrapper = styled.h2`
position: relative;
font-size: 1.5rem;
color: #ffffff;
font-weight: 600;
text-align: center;
text-transform: uppercase;
letter-spacing: 0.01em;
transform: scale3d(1, 1, 1);
opacity: 1;
> .before,
> .after {
position: absolute;
top: 0;
left: 0;
right: 0;
overflow: hidden;
background: #333333;
color: #ffffff;
clip: rect(0, 900px, 0, 0);
}
> .before {
left: 7px;
text-shadow: 1px 0 green;
animation: ${glitchEffect} 3s infinite linear alternate-reverse;
}
> .after {
left: 3px;
text-shadow: -1px 0 red;
animation: ${glitchEffect} 2s infinite linear alternate-reverse;
}
`;
function createAnimation() {
const single = `clip: rect(${Math.floor(
Math.random() * 100 + 1
)}px, 9999px, ${Math.floor(Math.random() * 100 + 1)}px, 0);`;
return css`
${single}
`;
}
export default function Glitch({ text }) {
return (
<Wrapper>
<div className="before">{text}</div>
{text}
<div className="after">{text}</div>
</Wrapper>
);
}
If you want to generate random animation, then you'll need to create the interval from Glitch
// First transform your "animation: ${glitchEffect} 3s infinite linear alternate-reverse;"
// into a "transition: text-shadow 500ms linear;"
// Since we're manually changing its value
import React, { useState, useEffect } from "react";
import styled from "styled-components";
import PropTypes from "prop-types";
const Wrapper = styled.h2`
position: relative;
font-size: 1.5rem;
color: #ffffff;
font-weight: 600;
text-align: center;
text-transform: uppercase;
letter-spacing: 0.01em;
transform: scale3d(1, 1, 1);
opacity: 1;
> .before,
> .after {
position: absolute;
top: 0;
left: 0;
right: 0;
overflow: hidden;
background: #333333;
color: #ffffff;
}
> .before {
left: 7px;
text-shadow: 1px 0 green;
transition: clip 300ms linear;
}
> .after {
left: 3px;
text-shadow: -1px 0 red;
transition: clip 200ms linear;
}
`;
function createAnimation() {
return {
clip: `rect(${Math.floor(Math.random() * 100 + 1)}px, 9999px, ${Math.floor(
Math.random() * 100 + 1
)}px, 0)`
};
}
export default function Glitch({ text }) {
const [glitchEffect, setGlitchEffect] = useState(createAnimation());
useEffect(() => {
const interval = setInterval(() => setGlitchEffect(createAnimation()), 500);
return () => {
clearInterval(interval);
};
}, []);
// now pass glitchEffect to a "style" prop to your pseudo elements
// See https://stackoverflow.com/a/28269950/3877913
return (
<Wrapper>
<div className="before" style={glitchEffect}>
{text}
</div>
{text}
<div className="after" style={glitchEffect}>
{text}
</div>
</Wrapper>
);
}
this.state.checkBool is true / false
The HTML structure like this, toggle class1 and class2
<div class='common class1'>
<div class='common class2'>
css looks like
common {
display: block;
background: grey;
}
.class1 {
position: absolute;
left: 1px;
right: auto;
top: 2px;
background: blue;
}
.class2 {
position: absolute;
left: auto;
top: 2px;
right: 30px;
background: yellow;
}
The styled component
const Wrapper = styled.div`
display: block;
background: grey;
// Should this part use props to check true or false?
${prosp => }
`
I am stuck on how to toggle classes
<Wrapper toggle={this.state.checkBool ? class1 :class2 }/>
You want to keep all the CSS in the styled.div and use the toggle prop to decide which CSS you should use for the component depending on its value.
Example
const Wrapper = styled.div`
display: block;
background: grey;
${props => {
if (props.toggle) {
return `
position: absolute;
left: 1px;
right: auto;
top: 2px;
background: blue;
`;
} else {
return `
position: absolute;
left: auto;
top: 2px;
right: 30px;
background: yellow;
`;
}
}}
`;
class App extends React.Component {
state = { checkBool: false };
componentDidMount() {
setTimeout(() => {
this.setState({ checkBool: true });
}, 1000);
}
render() {
return <Wrapper toggle={this.state.checkBool}> Foo </Wrapper>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<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>
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="root"></div>
I am creating a reusable modal, and everything is working but when I actually call the component, the enter transition is not working. Exit works perfectly. I get the error:
warning.js:45 Warning: Failed propType: transitionLeaveTimeout wasn't
supplied to ReactCSSTransitionGroup: this can cause unreliable
animations and won't be supported in a future version of React.Check
the render method of Modal
I have supplied enter and leave timeouts as instructed and still no luck.
import React from 'react';
import { render } from 'react-dom';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import '../../modal.css';
const Modal = React.createClass({
render(){
if(this.props.isOpen){
return (
<ReactCSSTransitionGroup transitionName={this.props.transitionName} transitionEnterTimeout={400} transitionLeaveTimeout={400}>
<div className="ui-modal" key={this.props.transitionName} {...this.props}>
{this.props.children}
</div>
</ReactCSSTransitionGroup>
);
} else {
return <ReactCSSTransitionGroup transitionName={this.props.transitionName} />;
}
}
});
const UiModal = React.createClass({
getInitialState(){
return { isModalOpen: false };
},
openModal() {
this.setState({ isModalOpen: true });
},
closeModal() {
this.setState({ isModalOpen: false });
},
setModalSize() {
this.setState({ isModalLarge: false });
},
render() {
const { openBtnText, header, subHeader, body, footer, optionalFooterText, closeBtnText, size } = this.props;
const modalSize = size === 'large' ? 'ui-modal-large' : 'ui-modal-small';
return (
<div className="ui-modal-trigger-container">
<h1>Modal small enter from bottom</h1>
<div className="button" onClick={this.openModal}>{ this.props.openBtnText }</div>
<Modal isOpen={this.state.isModalOpen} transitionName="modal-anim" id={modalSize}>
<h1 className="ui-modal-header">{header}</h1>
<div className="ui-modal-subheader">{subHeader}</div>
<div className="ui-modal-body">
{body}
</div>
<div className="ui-modal-footer">
<div className="ui-modal-footer-button-group">
<div className="ui-modal-footer-button button" onClick={this.closeModal}>{closeBtnText}</div>
<div className="ui-modal-optional-footer-text" onClick={this.closeModal}>{optionalFooterText}</div>
</div>
</div>
</Modal>
</div>
);
}
});
export default UiModal;
The only information I get back in the console is:
warning.js:45 Warning: Failed propType: transitionLeaveTimeout wasn't
supplied to ReactCSSTransitionGroup: this can cause unreliable
animations and won't be supported in a future version of React.Check
the render method of Modal
I am unsure how to fix since I have provided enter and leave timeouts already and it does not fix the issue.
The CSS for the modal is below:
.ui-modal-trigger-container {
width: 500px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 4px;
z-index: 0;
margin-top: 300px;
}
.ui-modal {
width: 450px;
margin: 0 auto;
top: 70%;
left: 35%;
padding: 20px;
background-color: green;
position: absolute;
z-index: 1;
border: 1px solid grey;
box-shadow: 0 0 5px 2px #fff;
background: white;
}
#ui-modal-small {
width: 450px;
margin: 0 auto;
top: 70%;
left: 35%;
padding: 20px;
background-color: green;
position: absolute;
z-index: 1;
border: 1px solid grey;
box-shadow: 0 0 5px 2px #fff;
background: white;
}
#ui-modal-large {
width: 100%;
height: 100%;
position: absolute;
z-index: 1;
top: 8%;
left:0%;
border: 1px solid #ccc;
background: white;
}
.ui-modal-header {
font-family: 'Flexo';
font-size: 28px;
border-bottom: 2px solid black;
width: 90%;
margin: 0 auto;
}
.ui-modal-subheader {
font-family: 'Flexo';
font-size: 13px;
width: 90%;
margin: 0 auto;
}
.ui-modal-body {
margin: 0 auto;
width: 90%;
padding: 10px;
}
.ui-modal-footer {
border-top: 2px solid black;
margin: 0 auto;
width: 90%;
}
.ui-modal-footer-button-group {
padding-top: 10px;
}
.ui-modal-footer-button {
float: right;
}
.ui-modal-optional-footer-text {
float: left;
color: #4099D4;
font-style: italic;
}
.modal-anim-enter {
opacity: 0.00;
transform: translateY(100%);
transition: all .5s;
}
.modal-anim-enter.modal-anim-enter-active {
opacity: 1;
transform: scale(1);
transition: all .5s;
}
.modal-anim-leave {
opacity: 1;
transform: translateY(100%);
transition: all .5s;
}
.modal-anim-leave.modal-anim-leave-active {
opacity: 0.00;
transform: translateY(100%);
}