The following code does not render the counter button to the page.
import { useState } from 'react';
import './App.css';
export default function App() {
<>
<Counter />
<Counter />
</>
}
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={ () => setCount(count 1)} >
Increment
</button>
<p>Count: {count}</p>
</>
);
}
However, this one does work with no problem. Why doesn't the first work to render the buttons to the page by creating a Counter component? Thank you.
import { useState } from 'react';
import './App.css';
export default function App() {
const [count, setCount] = useState(0);
const [otherCount, setOtherCount] = useState(5)
return (
<>
<button onClick={ () => setCount(count 1)} >
Increment
</button>
<p>Count: {count}</p>
<button onClick={ () => setOtherCount(otherCount 1)} >
Increment
</button>
<p>Count: {otherCount}</p>
</>
);
}
CodePudding user response:
You forgot to return
a value from a App function. To solve this error, make sure to explicitly use a return statement .
export default function App() {
return(
<div>
<Counter />
<Counter />
</div>
)
}
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={ () => setCount(count 1)} >
Increment
</button>
<p>Count: {count}</p>
</>
);
}