React Basics Intro

0

Category :

React and the JSX Syntax

React uses a funny syntax called JSX. JSX, which stands for JavaScript XML, is a syntax extension to JavaScript that enables developers to use XML (and, as such, HTML) to describe the structure of the user interface.

function showRecipe(recipe) {
  if (!recipe) {
    return 

Recipe not found!

; } return (

{recipe.title}

{recipe.description}

); }

In this case, the showRecipe function is using the JSX syntax to show the details of a recipe (i.e., if the recipe is available) or a message saying that the recipe was not found.

React Components

Components in React are the most important pieces of code. Everything you can interact with in a React application is (or is part of) a component. For example, when you load a React application, the whole thing will be handled by a root component that is usually called App.

The biggest advantage of using components to define your application is that this approach lets you encapsulate different parts of your user interface into independent, reusable pieces. Having each part on its own component facilitates reasoning, testing, and reusing each piece easily.

Defining Components in React

there are two types of React components

functional components
are simply "dumb" components that do not hold any internal state (making them great to handle presentation)
function UserProfile(props) {
  return (
    

{props.userProfile.name}

); }

class components
Are more complex components that can hold internal state. For example, if you are creating a component that will only show the profile of the user that is authenticated, you can create a functional component as follows:

However, if you are going to create a component to handle things that need to hold some state and perform more complex tasks, like a subscription form, you will need a class component. To create a class component in React, you would proceed as follows:
class SubscriptionForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      acceptedTerms: false,
      email: '',
    };
  }

  updateCheckbox(checked) {
    this.setState({
      acceptedTerms: checked,
    });
  }

  updateEmail(value) {
    this.setState({
      email: value,
    });
  }

  submit() {
    // ... use email and acceptedTerms in an ajax request or similar ...
  }

  render() {
    return (
      
{this.updateEmail(event.target.value)}} value={this.state.email} /> {this.updateCheckbox(event.target.checked)}} />
) } }

this component is defining three input elements (actually, two input tags and one button

this component is defining an internal state (this.state) with two fields: acceptedTerms and email

my thanks to this great blog post:
https://auth0.com/blog/react-tutorial-building-and-securing-your-first-app/

0 comments:

Post a Comment