I'm new in React.js. I would like to pass the same behaviour again but on the other two buttons like i did in the first.
I started with the following function to pass on my useReducer:
const hoverReducer = (state, action) => {
let newState;
switch (action.type) {
case 'true':
newState = {
transform: `scale(1.08)`,
backgroundColor: "transparent",
border: "none",
transition: `all 0.3s ease-in.out`
}
break;
case 'false':
newState = {
transform: `scale(1.0)`,
backgroundColor: "transparent",
border: "none",
}
break;
default:
throw new Error();
}
return newState;
}
then in my function Primary() i did this:
const initialState = {
transform: `scale(1.0)`,
backgroundColor: "transparent",
border: "none"
}
const [buttonStyle, setButtonStyle] = useReducer(hoverReducer, initialState)
const addHover = ()=>{
setButtonStyle({type: 'true'})
}
const removeHover = () =>{
setButtonStyle({type: 'false'})
}
my return:
return (
<div>
<button style={buttonStyle} onm ouseEnter={() => addHover()}
onm ouseLeave={() => removeHover()}
>
<img src="https://i.ibb.co/mJ6fzbt/gm-c.png" border="0" style={styleImg} />
</button>
<button >
<img src="https://i.ibb.co/znbBNmX/link-c.png" border="0" style={styleImg} />
</button>
<button >
<img src="https://i.ibb.co/HXXjyPT/twi-c.png" border="0" style={styleImg} />
</button>
</div>
)
Thanks in advance.
CodePudding user response:
You should create a new component with the hovering logic in that way each button you create has that logic in it. And accept src URL for the image plus anything you need as props.
MyButton
const MyButton = ({ styleImg, src }) => {
const initialState = {
transform: `scale(1.0)`,
backgroundColor: "transparent",
border: "none"
};
const [buttonStyle, setButtonStyle] = useReducer(hoverReducer, initialState);
const addHover = () => {
setButtonStyle({ type: "true" });
};
const removeHover = () => {
setButtonStyle({ type: "false" });
};
return (
<button
style={buttonStyle}
onm ouseEnter={() => addHover()}
onm ouseLeave={() => removeHover()}
>
<img src={src} border="0" style={styleImg} />
</button>
);
};
App
export default function App() {
return (
<div>
<MyButton src="https://i.ibb.co/mJ6fzbt/gm-c.png" styleImg={""} />
<MyButton src="https://i.ibb.co/znbBNmX/link-c.png" styleImg={""} />
<MyButton src="https://i.ibb.co/HXXjyPT/twi-c.png" styleImg={""} />
</div>
);
}