This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity postsor official solution page.
AI solution for React Coding Question on BFE.dev
1. the React Counter app
Sure, here's my solution:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
const handleDecrement = () => {
setCount(count - 1);
};
return (
<div>
<h2>Count: {count}</h2>
<button onClick={handleIncrement} data-testid="plus-btn">+</button>
<button onClick={handleDecrement} data-testid="minus-btn">-</button>
</div>
);
}
export default Counter;
In this solution, I've used the useState
hook to declare a state variable for the current count. I've also defined two event handlers, handleIncrement
and handleDecrement
, that update the count using the setCount
function.
In the return
statement, I'm displaying the current count along with two buttons that call the event handlers when clicked. I've also added data-testid
attributes to each button so that they can be tested using React Testing Library or a similar tool.