Ad
Triggering Specific Function On State Change
I'm trying to trigger a button to bounce when button is clicked and I'm trying to overcome a few things mentioned below:
- How do I stop useSpring to only execute when click = true (also on load)? A follow up question for this is. true is temporary how can I make it so that it reverts back to false after the animation is done or after x ms.
- How do I stop it from executing animation everytime useState() changes in Input?
- How to improve animation bounce to look more smooth? (optional)
export default function App() {
const [click, setClick] = useState(false);
const [input, setInput] = useState("");
const clicked = useSpring({
to: [{ transform: "scale(0.95)" }, { transform: "scale(1)" }],
from: { transform: "scale(1)" },
config: {
mass: 1,
tension: 1000,
friction: 13
}
});
const getInput = e => {
setInput(e.target.value);
};
return (
<div className="App">
<Input placeholder="type here" onChange={getInput} />
<animated.div style={clicked}>
<Button style={{ width: "300px" }} onClick={() => setClick(true)}>
Click me
</Button>
</animated.div>
</div>
);
}
Ad
Answer
I played around your code. I found a way to do it. First of all you should add a condition to useSpring to only play the animation if click is true. Secondly you should revert click back to false after the animation completed. I used timeout for the reverting part in this code.
export default function App() {
const [click, setClick] = useState(false);
const [input, setInput] = useState("");
const clicked = useSpring({
to: click
? [{ transform: "scale(0.95)" }, { transform: "scale(1)" }]
: [{ transform: "scale(1)" }],
from: { transform: "scale(1)" },
config: {
mass: 1,
tension: 1000,
friction: 13
}
});
const getInput = e => {
setInput(e.target.value);
};
const handleClick = () => {
setClick(true);
setTimeout(() => setClick(false), 700);
};
return (
<div className="App">
<Input placeholder="type here" onChange={getInput} />
<animated.div style={clicked}>
<Button style={{ width: "300px" }} onClick={handleClick}>
Click me
</Button>
</animated.div>
</div>
);
}
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad