I just started with React hooks and trying to have 3 buttons which I can click on and it should tell me how many times it was clicked. I can make them separately working but that's not performant.
Therefore I was looking for making it useful with just two classes: one for the buttons and the other one for the counter part. But now I'm struggling with calling the functions and separating (which one is clicked) the buttons.
import React, { useState } from "react";
import Counter from "./Counter";
const Buttons = () => {
const HandleClick = () => {
setCounter(count 1);
};
const [count, setCounter] = useState(0);
return (
<div>
<button className={"GoodBtn"} onClick={HandleClick}>
Good
</button>
<button className={"NeutralBtn"} onClick={HandleClick}>
Neutral
</button>
<button className={"BadBtn"} onClick={HandleClick}>
Bad
</button>
</div>
);
};
export default Buttons;
import React, { useState } from "react";
import Buttons from "./Buttons";
const Counter = () => {
const [count, setCount] = useState(0);
const teller = () => count 1;
return (
<div>
<h2>Statistics</h2>
<p>Good {Buttons.count}</p>
<p>Neutral {Buttons.count}</p>
<p>Bad {Buttons.count}</p>
</div>
);
};
export default Counter;
CodePudding user response:
import React, { useState } from 'react';
import Counter from "./Counter";
const Buttons = () => {
const[count,setCounter]= useState({
good: 0,
neutral: 0,
bad: 0
});
const HandleClick = (key) =>{
setCounter(state => ({...state, [key]: state[key] 1}));
}
return (
<div>
<button className={"GoodBtn"} onClick={HandleClick('good')}>Good</button>
<button className={"NeutralBtn"} onClick={HandleClick('neutral')}>Neutral</button>
<button className={"BadBtn"} onClick={HandleClick('bad')}>Bad</button>
<Counter counts={count} />
</div>
)
}
export default Buttons;
import React, { useState } from 'react';
import Buttons from "./Buttons";
const Counter = (props) => {
return(
<div>
<h2>Statistics</h2>
<p>Good {props.counts.good}</p>
<p>Neutral {props.counts.neutral}</p>
<p>Bad {props.counts.bad}</p>
</div>
)
}
export default Counter;
CodePudding user response:
You cannot just do Buttons.count
. Buttons is a React component, which needs to be created first, like: <Buttons />
.
If you want to wrap your button component with a counter you could just do:
const CountableButton = ({ onCounterChange, ...props }) => {
const [count, setCounter] = useState(0);
const handleClick = (event) => {
//to correctly change state variable based on previous value
setCounter((prevCounter) => prevCounter 1);
};
//Every time count changes trigger the onCounterChange function
React.useEffect(() => {
onCounterChange(count);
}, [count]);
return (
<button {...props} onClick={handleClick}>
Good
</button>
);
};
And you will use it like:
const App = () => {
const [count, setCount] = useState(0);
return (
<div>
<h2>Button clicked {count} times</h2>
<CountableButton onCounterChange={(value) => setCount(value)} />
</div>
);
};