Understanding the Base Features and Syntax – React

The COVID-19 pandemic started in Wuhan, China continues to infect and kill people all over the world. As of today Wednesday July 08, 2020 the world total confirmed cases and deaths are 11,900,855 and 545,728 respectively. Of course these numbers include reports from countries that are estimating (e.g., Peru and most Latin America countries) and countries (e.g., China) that for their political and financial gain report bogus numbers. Hopefully better treatments which will drastically reduce the symptoms and general public access vaccines will become short term realities. In the mean time, remember to wear a mask and gloves and keep social distancing.

As I have previously mentioned, I am currently taking a React course by O’Reilly by Maximilian Schwarzmuller. I just finished with the third chapter. I am hoping to start chapter 4 early tomorrow morning. Will let you know if that happens.

I took extensive notes on the subject covered by chapter 3 and experimented during the class. For that there is nothing like taking an on-line course. I was going to cover the entire chapter but realized there is a large amount of code which will not be easy to cover on this post. I decided to just cover the exercise at the end of the chapter.

When starting a React project you need to generate a new project and then modify and enhance to fit your needs. In this case I generated a project and then replaced and edited files as required by the assignment. I did encounter an issue or two which I will briefly discuss.

# **** open a new command prompt / console on my Windows 10 computer ****
Microsoft Windows [Version 10.0.18363.900]
(c) 2019 Microsoft Corporation. All rights reserved.

# **** changed directory to my current workspace ****
C:\Users\johnc>cd workspace1

# **** create a React project named: base-syntax ****
C:\Users\johnc\workspace1>create-react-app base-syntax

Creating a new React app in C:\Users\johnc\workspace1\base-syntax.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...


> core-js@2.6.11 postinstall C:\Users\johnc\workspace1\base-syntax\node_modules\babel-runtime\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"


> core-js@3.6.5 postinstall C:\Users\johnc\workspace1\base-syntax\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"


> core-js-pure@3.6.5 postinstall C:\Users\johnc\workspace1\base-syntax\node_modules\core-js-pure
> node -e "try{require('./postinstall')}catch(e){}"

+ react-dom@16.13.1
+ react@16.13.1
+ cra-template@1.0.3
+ react-scripts@3.4.1
added 1602 packages from 751 contributors and audited 1606 packages in 216.387s

61 packages are looking for funding
  run `npm fund` for details

found 4981 low severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details

Initialized a git repository.

Installing template dependencies using npm...
npm WARN tsutils@3.17.1 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ @testing-library/react@9.5.0
+ @testing-library/jest-dom@4.2.4
+ @testing-library/user-event@7.2.1
added 36 packages from 57 contributors and audited 1642 packages in 9.245s

61 packages are looking for funding
  run `npm fund` for details

found 4982 low severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details
Removing template package using npm...

npm WARN tsutils@3.17.1 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

removed 1 package and audited 1641 packages in 5.371s

61 packages are looking for funding
  run `npm fund` for details

found 4982 low severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details

Created git commit.

Success! Created base-syntax at C:\Users\johnc\workspace1\base-syntax
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd base-syntax
  npm start

Happy hacking!

# **** started the server *****
C:\Users\johnc\workspace1\base-syntax>npm start

> base-syntax@0.1.0 start C:\Users\johnc\workspace1\base-syntax
> react-scripts start

i 「wds」: Project is running at http://192.168.1.138/
i 「wds」: webpack output is served from
i 「wds」: Content not from webpack is served from C:\Users\johnc\workspace1\base-syntax\public
i 「wds」: 404s will fallback to /
Starting the development server...
Compiled successfully!

You can now view base-syntax in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.1.138:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

I decided to create a new React project in my workspace1 folder. Once in the desired folder, I created a new React project and named it base-syntax. After a few minutes the project was created.

I opened a Chrome page and on the command prompt issued the npm start command. The React application displayed the standard opening page. All was well. I stopped the server by entering ctrl-c on the command windows.

I replaced (deleted and copy) the files that were provided in the course to my project folder as follows:

Replaced the files from:  C:\Documents\React\CODES\S03\base-syntax–assignment-problem to:   C:\Users\johnc\workspace1\base-syntax

At that time I restarted the React server by issuing the npm start command. All went well. The Chrome browser displayed the following text:

1. Create TWO new components: UserInput and UserOutput
2. UserInput should hold an input element, UserOutput two paragraphs
3. Output multiple UserOutput components in the App component (any paragraph texts of your choice)
4. Pass a username (of your choice) to UserOutput via props and display it there
5. Add state to the App component (=> the username) and pass the username to the UserOutput component
6. Add a method to manipulate the state (=> an event-handler method)
7. Pass the event-handler method reference to the UserInput component and bind it to the input-change event
8. Ensure that the new input entered by the user overwrites the old username passed to UserOutput
9. Add two-way-binding to your input (in UserInput) to also display the starting username
10. Add styling of your choice to your components/ elements in the components - both with inline styles and stylesheets

For the assignment we need to implement the 10 tasks listed by the application. Liked the approach took by the instructor. I thought we had one less thing to look up during the development of the application.

The next step is to create a couple folders in which we will place the two React components called by the requirements list.

# **** opened a new command prompt ****
Microsoft Windows [Version 10.0.18363.900]
(c) 2019 Microsoft Corporation. All rights reserved.

# **** moved to my workspace ****
C:\Users\johnc>cd workspace1

# **** verified the name of the folder to move to ****
C:\Users\johnc\workspace1>dir
07/08/2020  07:33 AM    <DIR>          .
07/08/2020  07:33 AM    <DIR>          ..
07/08/2020  07:44 AM    <DIR>          base-syntax
07/01/2020  08:58 AM    <DIR>          HospitalsHillClimbing
06/22/2020  11:34 AM    <DIR>          learnangular5
07/02/2020  08:48 AM    <DIR>          react-complete-guide

# **** changed to the base-syntax folder ****
C:\Users\johnc\workspace1>cd base-syntax

# **** display the contents of the current folder ****
C:\Users\johnc\workspace1\base-syntax>dir
07/08/2020  07:44 AM    <DIR>          .
07/08/2020  07:44 AM    <DIR>          ..
10/26/1985  03:15 AM               310 .gitignore
07/07/2020  04:57 PM               375 how-to-use.txt
07/08/2020  07:40 AM    <DIR>          node_modules
10/19/2017  10:29 AM           347,209 package-lock.json
07/08/2020  07:45 AM               598 package.json
07/08/2020  07:44 AM    <DIR>          public
10/19/2017  10:29 AM           105,919 README.md
07/08/2020  07:50 AM    <DIR>          src

# **** moved to the source folder ****
C:\Users\johnc\workspace1\base-syntax>cd src

# **** using VSCode created the UserInput and UserOutput folders ****
C:\Users\johnc\workspace1\base-syntax\src>dir
07/08/2020  07:50 AM    <DIR>          .
07/08/2020  07:50 AM    <DIR>          ..
10/19/2017  10:35 AM                24 App.css
07/08/2020  07:44 AM             1,271 App.js
10/19/2017  10:29 AM               208 App.test.js
10/19/2017  10:29 AM                63 index.css
10/19/2017  10:29 AM               254 index.js
10/19/2017  10:29 AM             4,022 registerServiceWorker.js
07/08/2020  07:49 AM    <DIR>          UserInput    <=== folder created from VSCode
07/08/2020  07:50 AM    <DIR>          UserOutput   <=== folder created from VSCode

I opened a new command console. In it I navigated to the proper directory location. I am using the VSCode IDE for this project. I created two folders (UserInput and UserOutput), which will be used to host the two React components that we need to develop. While working with the code, I noticed a warning / error displayed in the Chrome console. It had to do with the size of the favicon.ico displayed by Chrome. After some research using Stack Overflow, I decided to update the manifest.json file from:

{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "192x192",
      "type": "image/png"
    }
  ],
  "start_url": "./index.html",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

To:

{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16",
      "type": "image/png"
    }
  ],
  "start_url": "./index.html",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

The change was in the “sizes” entry of the icons array. It seems that the issue was resolved. I then progressed through the different steps. The final set of files that were changed follow.

App.js:

import React, { Component } from 'react';
import './App.css';

// **** files do not need extension ****
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';

// **** ****
class App extends Component {

  // **** this is a property ****
  state = {
    username: 'supermax'
  }

  // **** 6. add a method to manipulate the state (=> an event-handler method) ****
  usernameChangedHandler = (event) => {
    this.setState({username: event.target.value});
  }

  // **** this is a method ****
  render() {
    return (
      <div className="App">

        {/* **** task list **** */}
        <ol>
          <li>Create TWO new components: UserInput and UserOutput</li>
          <li>UserInput should hold an input element, UserOutput two paragraphs</li>
          <li>Output multiple UserOutput components in the App component (any paragraph texts of your choice)</li>
          <li>Pass a username (of your choice) to UserOutput via props and display it there</li>
          <li>Add state to the App component (=> the username) and pass the username to the UserOutput component</li>
          <li>Add a method to manipulate the state (=> an event-handler method)</li>
          <li>Pass the event-handler method reference to the UserInput component and bind it to the input-change event</li>
          <li>Ensure that the new input entered by the user overwrites the old username passed to UserOutput</li>
          <li>Add two-way-binding to your input (in UserInput) to also display the starting username</li>
          <li>Add styling of your choice to your components/ elements in the components - both with inline styles and stylesheets</li>
        </ol>

        {/* **** 7. pass the event-handler method reference to the UserInput component and bind it to the input-change event **** */}
        <UserInput 
          changed={this.usernameChangedHandler} 
          currentName={this.state.username} />

        {/* **** output multiple UserOutput components in the App component (any paragraph texts of your choice) **** */}
        <UserOutput userName={this.state.username} />

        <UserOutput userName={this.state.username} />

        <UserOutput userName='Max' />
      </div>
    );
  }
}

export default App;

UserInput.js:

// **** MUST import for any component you create ****
import React from 'react';

// **** UserInput should hold an input element
//      ensure that the new input entered by the user overwrites the old username passed to UserOutput ****
const userInput = (props) => {

    // **** on-line style ****
    const inputStyle = {
        border: '2px solid red',
        height: 25
    };

    return <input 
        type="text" 
        style={inputStyle}
        onChange={props.changed}
        value={props.currentName} />;
}

// ***** MUST export for the object to be used ****
export default userInput;

UserOutput.js:

// **** MUST import for any component you create ****
import React from 'react';

// **** import style ****
import './UserOutput.css';

// **** UserOutput two paragraphs
//      Pass a username (of your choice) to UserOutput via props and display it there ****
const userOutput = (props) => {
    return (
        <div className="UserOutput">
            <p>Username: {props.userName} </p>
            <p>I hope I'll be overwritten!</p>
        </div>
    );
};

// ***** MUST export for the object to be used ****
export default userOutput;

And finally UserOutput.css:

.UserOutput {
    width: 60%;
    padding: 16px;
    margin: 16px;
    border: 2px solid black;
    background-color: #ccc;
    text-align: center;
}

If you are interested in more details I would suggest you to take the actual on-line course. As I mentioned, so far so good!!!

The entire code for this project can be found in my GitHub repository.

If you have comments or questions regarding this, or any other post in this blog, or if you would like for me to serve of assistance with any phase in the SDLC (Software Development Life Cycle) of a project associated with a product or service, please do not hesitate and leave me a note below. If you prefer, send me a private message using the following address:  john.canessa@gmail.com. I will reply as soon as possible.

Keep on reading and experimenting. It is the best way to learn, refresh your knowledge and enhance your developer toolset!

One last thing, many thanks to all 1,342 subscribers to my blog!!!

Keep safe during the COVID-19 pandemic and help restart the world economy.

John

Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.