Skip to content

Files

Latest commit

7064125 · Jul 25, 2020

History

History

03_State

03 State

In this example we introduce a basic React concept: handling State.

In this scenario we provide a default username and let the user update it.

We take as a starting point the example 02 Properties:

Summary steps:

  • Create an App component that holds the state. This state will contain the current username (with default value "defaultUserName"). This App component renders the Hello component. At first we create a simple stateless App component.
  • Update index.tsx file to include our App component.
  • Change App component to a stateful class component to hold the userName state.
  • Create a NameEdit component to let the user change the value of username. This changes the App state using a function from App.
  • Check everything works properly.

Prerequisites

Install Node.js and npm if they are not already installed on your computer.

Verify that you are running at least node v6.x.x and npm 3.x.x by running node -v and npm -v in a terminal/console window. Older versions may produce errors.

Steps to build it

  • Copy the content from 02 Properties and execute npm install.

  • Let's create an App component under a new file named app.tsx (this component will display the Hello component).

./src/app.tsx

import * as React from "react";
import { HelloComponent } from "./hello";

export const App = () => {
  return <HelloComponent userName="John" />;
};
  • Let's update index.tsx just to use the App component that we have just created.

./src/index.tsx

  import * as React from 'react';
  import * as ReactDOM from 'react-dom';
+ import { App } from './app';

- import { HelloComponent } from './hello';

  ReactDOM.render(
-    <HelloComponent userName="John" />,
+    <App />,
    document.getElementById('root')
  );
  • Now we can check that things are still working as expected.

    npm start
    
  • It's time to revisit app.tsx. We want to store the user's name and let the user updated it. We will use hooks to allow App functional components to make use of state (this works in React 16.8.2 and above if you have to use older versions you have to use a class component, check the "oldclasses_components" on the root of this repo for example). We will add _userName to the state.

Let's move this component to a class stateful component and define a state including userName, and pass this value to the Hello component.

./src/app.tsx

import * as React from "react";

import { HelloComponent } from "./hello";

export const App = () => {
+ const [name, setName] = React.useState('defaultUserName');
-  return <HelloComponent userName="John" />;
+  return <HelloComponent userName={name} />;
};
  • Again, we can do a quick check to test that everything works as expected.
npm start
  • Now it's time to create an NameEdit component. This component lets the user update his username and notifies with a callback to the parent control whenever the value of userName gets updated.

./src/nameEdit.tsx

import * as React from "react";

interface Props {
  userName: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}

export const NameEditComponent = (props: Props) => (
  <>
    <label>Update name:</label>
    <input value={props.userName} onChange={props.onChange} />
  </>
);

Side note: What is this Fragment or <> stuff? A way to create component that has multiple root elements (not a single parent). Available from React 16.2. As an alternative you can type:

  ...
  export const NameEditComponent = (props : Props) =>
    <React.Fragment>
      <label>Update name:</label>
      <input value={props.userName}
             onChange={props.onChange}
      />
    </React.Fragment>
}
  • In the app.tsx file, let's add a function to replace the state value of userName with the new one.

./src/app.tsx

import * as React from "react";
import { HelloComponent } from "./hello";
import { NameEditComponent } from './nameEdit';


export const App = () => {
  const [name, setName] = React.useState("defaultUserName");

+    const setUsernameState = (event: React.ChangeEvent<HTMLInputElement>) => {
+      setName(event.target.value);
+    }

- return <HelloComponent userName={name} />;
+      return (
+        <>
+          <HelloComponent userName={name} />
+          <NameEditComponent userName={name} onChange={setUsernameState} />
+        </>
+      );
};
  • Finally let's test everything works once more.

    npm start
    

About Basefactor + Lemoncode

We are an innovating team of Javascript experts, passionate about turning your ideas into robust products.

Basefactor, consultancy by Lemoncode provides consultancy and coaching services.

Lemoncode provides training services.

For the LATAM/Spanish audience we are running an Online Front End Master degree, more info: http://lemoncode.net/master-frontend