Topic Overview and Actualization

Hello there, adventure-loving coder!

Today is a big day, where we venture deeper into the fascinating cosmos of React, an immensely popular JavaScript library used for creating modern user interfaces. On today's journey, we'll focus on understanding and applying methods, nesting functional components, and passing primitive data and methods as props.

Here's a refresher on some basics. A functional component in React is a JavaScript function that accepts props (short for properties) as an argument and returns a React element.

Imagine building a starship, where each functional component represents a different part, such as the thrusters or the cockpit. In our cockpit (which we'll regard as a functional component), we will define methods that act as controls for the thrusters. With props, we can pass control from the cockpit to the thrusters. Fascinating, isn't it?

Let's break it down!

What Are Methods, and How Do We Define Them in React?

Methods in JavaScript are actions associated with an object. They are blocks of code that perform specific tasks. These methods are defined inside of a functional component before the return statement, as shown below:

const Spaceship = () => {
  const startThrusters = () => {
    console.log("Thrusters are ON");  
  }
  return (
    <button onClick={startThrusters}>Start Thrusters</button>  
  );
}
Using Methods in Functional Components

An advantage of methods is they can handle virtually any type of event, ranging from a simple mouse click, to more elaborate ones such as form submissions, providing a React component with dynamic functionality.

Let's extend the functionality of our spaceship. How about we add a method that checks the spaceship's fuel level?

const Spaceship = () => {
  const fuelStatus = () => {
    let fuelLevel = 70; // in percentage
    if (fuelLevel > 50) {
      return "Fuel Status: Good";
    } else {
      return "Fuel Status: Low";
    }
  };
  return (
    <h3>{fuelStatus()}</h3>
  );
}
Nesting Functional Components

Sometimes, a component might be designed to exist within another component. This is called "nesting". In our spaceship example, the thruster could be seen as a component nested within our spaceship component:

const Thruster = () => {
  return (
    <p>Thruster is ready!</p>  
  );
}

const Spaceship = () => {
  return (
    <div>
      <Thruster />
    </div>
  );
}

Great! Now our spaceship has thrusters!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal