const Component = () => {
const [newName, setnewName] = useState('');
const updateName = (max: number) => {
//logic to update newName
};
return (
<>
<div>{newName}</div>
</>
);
};
export default Component;
When ever the newName variable's value changes I want to add some effect in the ui for it. Is there any way that this can be done?
CodePudding user response:
Yes. You can use the useEffect hook to achieve this, and add the newName state as a dependency.
For example, take a look at the following. I will demonstrate through console.log("hey, newName changed")
every time the variable state changes.
const Component = () => {
const [newName, setnewName] = useState('');
useEffect(() => {console.log("hey, newName changed!"}, [newName])
const updateName = (max: number) => {
};
return (
<>
<div>{newName}</div>
</>
);
};
export default Component;
Import it with useState.
Now, you may ask "yes, but youre only consoling something out, not actually doing anything with the CSS transition". Rest assured, you can take a similar approach.
The useEffect hook is simply a function that watches for state change. From the callback function, just add your custom css transition class, or fire a function that changes the CSS.
As I am not sure what kind of transition effect you want as you did not specify it in your question, so forgive me for not being able to provide a specific example. I hope this helps you.
CodePudding user response:
use useEffect and dependancy in to change state and using that state you can update class, and then write aniamtion css for that class , hope this will help...
import React from "react";
import "./App.css";
function App() {
const [newName, setnewName] = React.useState('Lorem');
const [transition, setTransition] = React.useState(false)
React.useEffect(()=>{
setnewName('ipsum')
setTransition(true)
},[newName])
return (
<>
<h1 classNane={`${transition?'animate':''}`} >{newName}</h1>
</>
);
}
export default App;