'How to use condition for adding or removing closing tags containing htms in JSX?
Fade tag which is animation tag under package react-reveal
I want to use Fade tag for the animation only when my mouse come under div tag else I don't want to animate the div className=card-container but
to do this I have to repeat the code div className=card-container like so
{ isHover ? <Fade>div className="card-container"</Fade> : div className="card-container" }
Is there alternative to do remove Fade tag only in simple way.
import React from "react";
import styled from "styled-components";
import { Fade } from "react-reveal";
export default function CardSection() {
const [isHover, setIsHover] = React.useState(false);
function getIsHover() {
setIsHover((prev) => !prev);
}
return(
<CardSectionStyled>
<div onMouseEnter={getIsHover}>
<div className="card-container">
{/* Here I have to repeat p tag in order to add and remove Fade tag */}
{isHover ? <Fade right duration={1500} delay={500}>
<div className="card-left">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab
</p>
</div>
</Fade> :
<div className="card-left">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab
</p>
</div>
}
</div>
</CardSectionStyled>
);
}
const CardSectionStyled = styled.section`
.card-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
p {
padding: 1.5rem 0;
}
`;
Solution 1:[1]
React elements are values (specifically, they're objects), you can put them in variables. So you can put that div in a variable (say, cardLeft) and then use that in the two places you need it:
export default function CardSection() {
const [isHover, setIsHover] = React.useState(false);
function getIsHover() {
setIsHover((prev) => !prev);
}
// *** Put the React element for the `div` in a variable
const cardLeft = (
<div className="card-left">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab
</p>
</div>
);
// *** Use `cardLeft` in the two places you need it below
return(
<CardSectionStyled>
<div onMouseEnter={getIsHover}>
<div className="card-container">
{isHover
? <Fade right duration={1500} delay={500}>
{cardLeft}
</Fade>
: cardLeft
}
</div>
</div>
</CardSectionStyled>
);
}
(I also added a missing </div>.)
There are a dozen different ways to spin it. For instance:
export default function CardSection() {
const [isHover, setIsHover] = React.useState(false);
function getIsHover() {
setIsHover((prev) => !prev);
}
let cardLeft = (
<div className="card-left">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab
</p>
</div>
);
if (isHover) {
cardLeft = (
<Fade right duration={1500} delay={500}>
{cardLeft}
</Fade>
);
}
return(
<CardSectionStyled>
<div onMouseEnter={getIsHover}>
<div className="card-container">{cardLeft}</div>
</div>
</CardSectionStyled>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
