Reputation: 7028
How to use State in functional component of React ?
I have a component like below
import React, { useState } from 'react';
function App() {
const [count] = React.useState(0); //Set State here
function count_checkbox() {
var applicable = [];
const cbs = document.querySelectorAll('input[class*="checkbox_value"]');
cbs.forEach((cb) => {
if (cb.checked) {
applicable.push(parseInt(cb.value));
}
});
this.setState({ count: applicable.length }) //Update State here
}
return (
<div className="App">
<input type="submit" id="button" value="{ this.state.count }"/> //Use State here
</div>
);
}
export default App;
But State is not working here.
Upvotes: 1
Views: 4442
Reputation: 1663
A functional component is just a plain javascript function which takes props as an argument and returns a react element.
A stateless component has no state, it means that you can’t reach this.state
and this.setState()
inside it. It also has no lifecycle so you can’t use componentDidMount and other hooks.
import React, { useState } from 'react';
function App() {
const [count, setCount] = React.useState(0); //Set initial state here
function count_checkbox() {
var applicable = [];
const cbs = document.querySelectorAll('input[class*="checkbox_value"]');
cbs.forEach((cb) => {
if (cb.checked) {
applicable.push(parseInt(cb.value));
}
});
setCount(applicable.length) //Update State here
}
return (
<div className="App">
<input type="submit" value={`Apply tax to ${ count } item(s)`} /> //You Can't use this.state.count here
</div>
);
}
export default App;
Upvotes: 1
Reputation: 2635
this.setState
is unsed to update state in class components. In order to update state in functional component you need to update it with appropriate function.
useState returns 2 values first is current state value and second one function to update that state
const [count, setCount] = React.useState(0);
Whenever you want to update count
state you need to update with setCount
function
function count_checkbox() {
...
setCount(applicable.length); //Update State here
}
You can access count
in your useEffect like below:-
useEffect(() => {
alert(count);
}, [count])
Upvotes: 2
Reputation: 2112
Updating the state in a functional component is different from a class component. The useState
hook returns an array consisting of the value and a setter.
You then call the setter function to update the value of the state.
const [count, setCount] = React.useState(0);
function count_checkbox() {
...
setCount(applicable.length)
}
Upvotes: 2
Reputation: 63
states should be like this
const [count,setCount] = React.useState(0); //setState
function count_checkbox() {
var applicable = [];
const cbs = document.querySelectorAll('input[class*="checkbox_value"]');
cbs.forEach((cb) => {
if (cb.checked) {
applicable.push(parseInt(cb.value));
}
});
setCount(applicable.length) //Update State here
}
setCount sets the state count.
Upvotes: 2