Stateful function components

We've mentioned that function components can have state. In this section, we'll add state to our function Confirm component, to force users to click the Cancel button twice before closing it, as follows:

  1. We'll start by defining and initializing state for the number of times the Cancel button is clicked, by adding the highlighted line:
const Confirm: React.SFC<IProps> = props => {

const [cancelClickCount, setCancelClickCount] =
React.useState(0);

const handleOkClick = () => {
props.onOkClick();
};
...
}

 This line of code looks a little strange, so let's break it down:

  • React.useState is a React function that lets us create state, passing in a default value as a parameter. In our case, we pass it a default value of 0.
  • The useState function returns an array containing two elements:
  • The first array element contains the current value of state
  • The second array element contains a function to set state to a different value
  • We destructure the array and store the first array element (the state value) in cancelClickCount, and the second array element (the function to set state) in setCancelClickCount.
  • The rest of the function now has access to the cancel click count, via the cancelClickCount variable. The function is also able to increment the cancel click count, via the setCancelClickCount variable.
  1. Let's refactor the handleCancelClick arrow function to increment cancelClickCount, and only invoke the onCancelClick prop if the count has reached 2:
const handleCancelClick = () => {
const newCount = cancelClickCount + 1;
setCancelClickCount(newCount);
if (newCount >= 2) {
props.onCancelClick();
}
};

 Now, functions to set the piece of state take in the new state as their parameter.

  1. Next, we'll change the Cancel button caption, to say Really? after the first click:
<button className="confirm-cancel" onClick={handleCancelClick}>
{cancelClickCount === 0 ? props.cancelCaption : "Really?"}
</button>

So, we access the state value in JSX through the variable we destructured when the state was defined.

If we give this a try in the running app, we should find the Cancel button text changes to Really? after the first click, and the confirmation dialog closes after the second click.

After we've got our heads around the code needed to define state, accessing and setting state is fairly simple and elegant.

Let's continue to the next section, and look into how we can hook into a function component's life cycle events.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.88.157