In example 05 we learned how to remove state from a child control just to have clear governance of state.
It's time to make some cleanup, let's simplify nameEdit.tsx component and modify it to a stateless component.
We take 05 Refactor as reference.
Summary steps:
- Update nameEdit.tsx and modify it to a stateless component.
Install Node.js and npm (v6.6.0 or newer) 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 -vandnpm -vin a terminal/console window. Older versions may produce errors.
-
Copy the content from 05 Refactor and execute
npm install. -
Update nameEdit.tsx and modify it to stateless component. It should look like this:
import * as React from 'react';
import {Fragment} from 'react';
interface Props {
editingUserName : string;
onEditingNameUpdated : (newEditingName : string) => void;
onNameUpdateRequest : () => void;
}
export const NameEditComponent = (props : Props) =>
<div>
<label>Update Name:</label>
<input value={props.editingUserName}
onChange={(e) : void => props.onEditingNameUpdated((e.target as HTMLInputElement).value)} />
<button className="btn btn-default" onClick={props.onNameUpdateRequest}>Change</button>
</div>Side note: during the refactory we have changed this.props to props. This is a required step as NameEditComponent is no longer a class but a function. During runtime, this is now undefined, so obviously then this.props fails.
Side note 2: applying currying and Fragments, the code for NameEditComponent looks like this:
const onChange = (props: Props) => (event) => {
props.onEditingNameUpdated(event.target.value)
}
export const NameEditComponent = (props : Props) =>
<>
<label>Update Name:</label>
<input value={props.editingUserName} onChange={onChange(props)} />
<button className="btn btn-default" onClick={props.onNameUpdateRequest}>Change</button>
</>
- Now we can run the example and we get the same results
npm start