How to pass data from parent to child component

Passing state through the props object in React

State is the data that flows through our application and in React we pass state around from parent to child component.
The vehicle we use to pass state between components is a Javascript object named props.

We already said that functional components are just functions, and like any function they can take arguments.
React functional components take a props argument that represents the state of the application.

For example, we can have a component that displays a list of students. The component is named Students and is defined in a file called Students.js
For this example we have some data that represents a list of students as a Javascript array.
Each element of the array is an object that represents a student with few properties:

const students = [                   
   {                                  
     name: 'Carol',                   
     age: 20,                         
     likes: 'Math'                   
   },                                 
   {                                  
     name: 'Alan',                    
     age: 22,                         
     likes: 'English'                
   }                              
 ]                                 ]           

Normally, in React, data will come from some external source, like a database or an API.
For our example the array is defined inside the Students component file and we want to render one child component for each student in our list.
The child component will be called Student and will render properties like name, age and likes.

Let's stop here for a minute and recap.
We have defined a list of students in the Students component and we want to render each student properties in the Student component. How do we pass the data from the parent component Students to the child component Student?
We pass it via the props object.

The props object has the job to pass data from the parent component to the child component. Here's how we do it.

At the top of the Students component we import the Student component.
Then we render one Student component for each student in the original array.
We pass an attribute called student to each Student component.
This attribute is set to one of the array elements that represents one student.
Here's the code:

import Student from './Student';

const Students = () => {
  return (
    <div className="student-list">
      <h2>Students</h2>

      <Student student={students[0]} />
      <Student student={students[1]} />
      <Student student={students[2]} />
    </div>
  )
}

Note that when we pass the student attribute inside the Student component, we must include the student value in curly braces.
This is because we are inserting Javascript syntax (students[0]) inside JSX syntax. Inside JSX, brackets are used to interpolate Javascript.
The student object is passed down to the Student component as a props object and can be displayed by calling props.student.

Here's how we display the student data inside the Student component:

const Student = props => {
  return (
    <div>
      <h3>{props.student.name}</h3>
      <p>Best in: {props.student.bestIn}</p>
    </div>
  )
}

As you can see, we pass the props object to the Student component as an argument to the function.
Inside the function, we have access to props.student which is a student object from the students array.
The student object has three properties: name, age, and likes that we can access by calling them.

You probably noticed that we iterate through the students array one object at a time. This is OK for this contrived example but in real life we would need to use an array method to iterate through the array.
Tomorrow we will look at the array.map()method that helps us iterate through the students.


Did you like this article? Share it with your friends.
I write daily about front-end and back-end web technologies.
You can receive all my articles in your inbox by subscribing to my newsletter. Just click the button below. No spam, just good, useful content. Guaranteed!

Follow me on Twitter

React components and state

A quick discussion of state and components in React

React is a way to manage state in a complex application.
Today's web applications tend to become very complex very fast.
React allows us to manage this complexity by displaying components depending on how the state of our application changes over time. We update the state and React will take care of the rest.

But, what is state?

The web was originally built as a way to link documents together. These documents have state. For example, the text in a static html page is considered to be state. The links in the same page, are also state.

In a static web site, though, state is not updated, it’s replaced. If you want to change state, like the page content for example, you reload the whole page.
In static web sites there is no need to update the existing state, because when there are changes to state, you replace the whole document.

In dynamic web applications, however, state changes based on user interaction.
If a user clicks a button or moves the mouse in the application, an event is generated and this event may trigger a change of state.
For example, a hidden component may be revealed on mouse over.

The job of React is to manage all the state updates that occur in modern web applications.
React also helps create a separation between front end and back end of an application, so there is less dependency among these parts.

React components

The basic structure of a React application is made up of components.
Components are Javascript functions or classes and they are defined in a series of files inside a components directory in our file structure.

Sometimes you see multiple components in one file, but for the purpose of keeping things organized it's better to create a file for each component.

create-react-app adds a src directory to our project and we save components inside this directory.
We name the file that defines a component the same name as the component name. So, if our component name is BasicButton, it will live in a file called BasicButton.js

In the component file, at the top, we need to import React or it won't recognize the JSX syntax.
Once we have created our component, we export it at the end of the file, so it's accessible to other components that need it.

Below is the basic structure of a component file, with the React import at the top, the component definition, and the export line at the bottom.

// /src/components/BasicButton.js

import React from 'react';

const BasicButton = () => {
  return(
    <button>Click me, I'm a button</button>
  )
}

export default BasicButton;Below is how we import the BasicButton component into another file:
// /src/App.js

import BasicButton from './components/BasicButton';

Components pass state around between them through an object called props.
We will look at how this mechanism work in tomorrow's article.


Did you like this article? Share it with your friends.
I write daily about front-end and back-end web technologies.
You can receive all my articles in your inbox by subscribing to my newsletter. Just click the button below. No spam, just good, useful content. Guaranteed!

Follow me on Twitter

React components

How to build functional components in React

Components are the basic blocks of React. At their core, components are just Javascript functions or classes that have one thing in common, they all return JSX.
Of course there's more to that, and we will look at components in more detail later, but this is the main concept to remember at the moment.

As I said, components can be either Javascript function or classes. If a components is made out of a function it's called a functional component.
Let's see what a functional component looks like by creating one.

In the following code we create a BasicButton component.
Note that the variable name used to initialize the component is capitalized. Component names need to be capitalized in React, or they won't work.
The variable is assigned a function, in this case an arrow function, that returns a <button> element with some text in it.
Note also that we are using an arrow function to define the component. We could have used a regular function definition with the function keyword, but the convention in React is to use arrow functions so we will stick with the convention.

const BasicButton = () => {                  
  return(                                    
    <button>Click me, I'm a button</button>  
  )                                          
}   

Note that the <button> syntax resembles HTML, but it's actually JSX. We are writing JSX inside a Javascript file, and since we have imported React at the top of the file, the JSX is transpiled down to Javascript and HTML before it's passed to the browser, and it all works smoothly.

To use the component we have just created, we need to add it somewhere, but where?

If you remember, in a previous article I mentioned that create-react-app creates two directories inside our project, a public directory and a src directory.
The public directory has an index.html file that is the entry point of our application. The React application is mounted inside a div element inside this index.html file.
What is mounted inside the root element, is an App component, defined in the App.js file inside the src directory.
The App.js file looks like this:

function App() {
  return (
    <div className="App">
      <h1>Students</h1>
      <Students />
    </div>
  );
}

We can add our new BasicButton component inside the App component, and it will
be rendered in the page.

<div className="App">
  <h1>Students</h1>
  <Students />

  // Rendering the BasicButton component
  <BasicButton />

</div>

In this article we have seen how to create a functional component and how to include it into our application.

There is another type of component, the class component, but before talking about class components we need to talk about another important feature of React: the way it manages state.

How to jumpstart a React application

Quickly initialize a React app with create-react-app

create-react-app is a npm module that sets up a skeleton React application from scratch. It will quickly and seamlessly create a scaffolding with all the directories, files, and libraries required to jumpstart an application.
You can find the project homepage here.

create-react-app sets up the environment for developing and running a React application. It creates a project directory and initializes a package.json file with all the required dependencies, including Babel, and tools like react-script that do the transpiling automatically.

This is the command we run to create a React application. Replace app-directory with the name of the directory that contains the application.

npx create-react-app app-directory

Running this command creates the named directory and a package.json file inside of it.
It then downloads all the necessary npm modules and adds a start script that we can use to start the React application.

We can also run create-react-app from inside an existing directory, but we should make sure the directory is empty or we wouldn’t be able to run the command:

// run the command from inside a directory  

npx create-react-app .

We can run the start script either with npm or yarn, from inside the project directory.

npm start  

// or   

yarn start

The application will be started and automatically served on port 3000.
We can open the base application in our browser by navigating to http://localhost:3000

Create-react-app builds a directory structure with a public directory and a src directory.
Within the public directory there's an index.html file that is used as the entry point of our application.
index.html contains a div element with an id of root that functions as the mount point for the React application.
The whole React application will be contained within this root element, and as
we will see, it will be built up of many components.

Next, we are going to see how to build React functional components.


Did you like this article? Share it with your friends.
I write daily about front-end and back-end web technologies.
You can receive all my articles in your inbox by subscribing to my newsletter. Just click the button below. No spam, just good, useful content. Guaranteed!

Follow me on Twitter

Function invocation with the apply() and call() methods

The "this" parameter in the context of Javascript functions

We have seen in previous articles how the this parameter is set differently depending on how the function is invoked.

this can be set to the global or window object if the function is invoked as a regular function, it's set to the object that calls the function when the function is invoked as a method, and it's set to the instance of the object created when the function is invoked as a constructor function.
What if we want to set this to an arbitrary object?

We can do that by using the call() and apply() methods of the function.
Since functions are first class objects in Javascript, they also have properties and methods that we can use.
The call() and apply() methods are two related built in methods that each function object has that we can use to set this.

The call() and apply() methods take two parameters.
The first parameter is the object that we want to set as this.
The second parameter refers to arguments passed to the function on invocation.
The difference between the call() and the apply() method is in the way they accept the second parameter.

call() will take in a list of arguments, while apply() will take in an array of arguments.
Below is an example of using call() and apply().
We define two different objects, pugliese and focaccia, and a bake() function.
The bake() function prints out a list of the arguments passed to it when it's invoked and also prints out this.

const pugliese = {
  name: 'Pane pugliese',
  description: 'Round and crunchy'
}

const focaccia = {
  name: 'Focaccia',
  description: 'Soft and flat'
}

function bake() {
  console.log(arguments);
  console.log("'this' is:", this);
}

bake.call(pugliese, 'water', 'flour', 'salt');

// prints out:
// [Arguments] { '0': 'water', '1': 'flour', '2': 'salt' }
// 'this' is: { name: 'Pane pugliese', description: 'Round and crunchy' }


bake.apply(focaccia, ['oil', 'water', 'flour', 'salt']);

// prints out:
// [Arguments] { '0': 'oil', '1': 'water', '2': 'flour', '3': 'salt' }
// 'this' is: { name: 'Focaccia', description: 'Soft and flat' }

As you can see, this is set to the object we pass to the function.
The call() and apply() methods are useful when we want to explicitly set the value of this at function invocation.


Did you like this article? Share it with your friends.
I write daily about front-end and back-end web technologies.
You can receive all my articles in your inbox by subscribing to my newsletter. Just click the button below. No spam, just good, useful content. Guaranteed!

Follow me on Twitter

Loading more posts…