Skip to content

Latest commit

 

History

History
81 lines (56 loc) · 1.83 KB

readme.md

File metadata and controls

81 lines (56 loc) · 1.83 KB

02 Properties

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

We add a username property and display it in the hello component.

We take as startup point the example 01 Hello React:

Summary steps:

  • hello stateless component: create a property to hold the username value.
  • Let's provide a value from our parent control.

Prerequisites

Install Node.js and npm (v6.6.0) 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 01 HelloReact and execute:

    npm install
    
  • Let's update hello.tsx to add a new property (userName) and display it using interpolation ({userName}):

hello.tsx

import * as React from 'react';

- export const HelloComponent = () => {
+ export const HelloComponent = (props: {userName : string}) => {
  return (
-    <h2>Hello component !</h2> 
+    <h2>Hello user: { props.userName } !</h2>
  );
}

Side note: using interfaces and ES6, the change looks like this:

import * as React from 'react';

+ interface Props {
+   userName: string;
+ }

- export const HelloComponent = () => {
+ export const HelloComponent = (props: Props) => (
-   return (
-    <h2>Hello component !</h2> 
+    <h2>Hello user: { props.userName } !</h2>
  );
-}
  • Let's update main.tsx and provide a value to the userName property:
  import * as React from 'react';
  import * as ReactDOM from 'react-dom';
  import { HelloComponent } from './hello';

  ReactDOM.render(
-    <HelloComponent />,
+    <HelloComponent userName="John" />,
    document.getElementById('root')
  );
  • Let's test the sample:
npm start