Categories
React Tips

React Tips — The Basics

React is one of the most popular libraries for creating front end apps. It can also be used to create mobile apps with React Native.

In this article, we’ll go back to the basics and look at basic things that we should be aware of that can let us create React apps easier.

JSX Code are Expressions

When writing React code, we have to remember that JSX code is just JavaScript expressions. This means that they can be used anywhere that JavaScript expressions can be used like assigning them to variables, nesting them, using them as properties of objects, returning them in functions, etc.

For instance, we can do common operations with them as follows:

import React from "react";
const title = <h1>Hello</h1>;

export default function App() {
  return <div className="App">{title}</div>;
}

In the code above, we have the title constant that’s assigned to an h1 element. We then put it inside the App component.

If we remember this, then we won’t have any difficulty with incorporating JSX code in our React app.

JSX Can Be Nested

We can nest JSX elements within each other. For instance, we can nest multiple components within another component as follows:

import React from "react";

export default function App() {
  return (
    <div>
      <p>foo</p>
      <p>bar</p>
    </div>
  );
}

In the code above, we have the div element that wraps around 2 p elements.

We can access child components by the special children prop in our own component. For instance, we can write the following code to do that:

import React from "react";

const Foo = ({ children }) => {
  return <div>{children}</div>;
};

export default function App() {
  return (
    <Foo>
      <p>foo</p>
      <p>bar</p>
    </Foo>
  );
}

In the code above, we have the Foo component that takes the children prop which is rendered in the component by returning it inside a div.

Then in App , we put in 2 p elements inside Foo and lets us display them within the Foo component. This way, we can nest items in our own components with ease.

HTML and JSX are Different

HTML and JSX are different. JSX is a JavaScript code that looks like HTML. As we saw above, the JSX code is just JavaScript in a different form. They shouldn’t be confused with HTML even though they look kind of the same.

Differences include all tags have to be closed and the class attribute in HTML is called className in JSX.

For instance, in HTML, we have tags like img that that don’t close in HTML. We can add an image in HTML by writing the following code:

<img src='https://images.unsplash.com/photo-1565598478542-4dfb41f0e9e2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80' alt='work'>

On the other hand, in JSX, we have to close the tag. Therefore, we write the following:

import React from "react";

export default function App() {
  return (
    <img
      src="https://images.unsplash.com/photo-1565598478542-4dfb41f0e9e2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
      alt="work"
    />
  );
}

In the code above, we have a slash at the end of the img tag. This is required rather than optional.

To add the class attribute to an element, we can write the following code in HTML:

<div class='foo'>
  foo
</div>

We added the foo class with the class attribute.

In JSX, we have to write the following code:

import React from "react";

export default function App() {
  return <div className="foo">foo</div>;
}

The className prop lets us set the class attribute of the div element rather than class . This is because class is a reserved word in JavaScript, so it can’t be used as a prop name.

Also, in JavaScript, the className property is the property of a DOM element object that’s used to set the class attribute value.

Therefore, we must remember that the prop to set the class attribute is className in React and JSX.

Components and Props

A React app has components that take props. Props are data that are passed down from a parent to a child.

Props can be any kind of data. They can be objects, primitive values, functions, etc.

If we pass in a function as a prop value, then we can call functions that’s in the parent in the child component.

For instance, we can pass in several props as follows:

import React from "react";

const Button = ({ displayAlert, text }) => {
  return <button onClick={displayAlert}>{text}</button>;
};

export default function App() {
  const displayAlert = () => alert("alert");
  return <Button text="click me" displayAlert={displayAlert} />;
}

In the code above, we passed in a function displayAlert into the Button component, which is a child component for App , then we called it in Button when the button is clicked.

We also pass in the text prop with the value 'click me' to display the text on the button.

Conclusion

JSX is just JavaScript expressions. Therefore, we can put expressions anywhere by writing it just like any other expression.

HTML and JSX are different. They look similar but JSX is JavaScript and HTML is HTML.

Finally, React apps are composed of components which take props. Props are data that are passed in from a parent component to a child and can be any JavaScript data type.

Categories
React Tips

React Tips — Clean Syntax

React is the most used front end library for building modern, interactive front end web apps. It can also be used to build mobile apps.

In this article, we’ll look at how to write React components in a clean way.

Toggling Components

We can toggle components by using ternary expressions. For instance, we can write the following code to do that:

import React from "react";

const Foo = () => <p>foo</p>;
const Bar = () => <p>bar</p>;

export default function App() {
  const [toggle, setToggle] = React.useState(false);

  return (
    <>
      <div>
        <button onClick={() => setToggle(toggle => !toggle)}>Toggle</button>
        {toggle ? <Foo /> : <Bar />}
      </div>
    </>
  );
}

In the code above, we have Foo and Bar components that we want to toggle between. We used the ternary expression to do that in the following code:

{toggle ? <Foo /> : <Bar />}

The code above returns Foo or Bar given the value of toggle . Therefore, when we click the Toggle button, the setToggle method is called, and then React renders Foo or Bar depending on whether toggle is true or not.

If we want to toggle a single component on and off, we can write the following code:

import React from "react";

const Foo = () => <p>foo</p>;

export default function App() {
  const [toggle, setToggle] = React.useState(false);

  return (
    <>
      <div>
        <button onClick={() => setToggle(toggle => !toggle)}>Toggle</button>
        {toggle ? <Foo /> : undefined}
      </div>
    </>
  );
}

We can put null or undefined in JSX if we don’t want to render anything. Also, we can write:

import React from "react";

const Foo = () => <p>foo</p>;

export default function App() {
  const [toggle, setToggle] = React.useState(false);

  return (
    <>
      <div>
        <button onClick={() => setToggle(toggle => !toggle)}>Toggle</button>
        {toggle && <Foo />}
      </div>
    </>
  );
}

In the code above, we used the && operator to show Foo only when toggle is true .

Destructuring Props and State

Destructuring props and state are great because we can selectively choose which the props and state to render according to our preference.

We can destructure props by writing the following for function components:

import React from "react";

const Person = ({ firstName, lastName, age }) => (
  <p>
    {firstName} {lastName} {age}
  </p>
);

export default function App() {
  return (
    <>
      <div>
        <Person firstName="Jane" lastName="Smith" age={20} />
      </div>
    </>
  );
}

In the code above, we pass in the firstName , lastName , and age props into Person , then we used the destructuring syntax in the parameter of Person to extract the props from the parameters.

Therefore, we see:

Jane Smith 20

displayed on the screen as we pass in the props in App and render them in Person .

For class components, we can destructure props and state as follows:

import React from "react";

class Person extends React.Component {
  render() {
    const { firstName, lastName, age } = this.props;
    return (
      <p>
        {firstName} {lastName} {age}
      </p>
    );
  }
}

export default function App() {
  return (
    <>
      <div>
        <Person firstName="Jane" lastName="Smith" age={20} />
      </div>
    </>
  );
}

In the code above, we have the Person class component, that has the render method. We access the props by using this.props and then we destructure the properties of this.props into their own variables.

Then we render them in the p element. Therefore, we’ll get the same result as before.

Likewise, we can destructure states as follows:

import React from "react";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posCount: 0,
      negCount: 0
    };
  }

  render() {
    const { posCount, negCount } = this.state;
    return (
      <div>
        <button
          onClick={() => this.setState(count => ({ posCount: posCount + 1 }))}
        >
          Increment
        </button>
        <button
          onClick={() => this.setState(count => ({ negCount: negCount - 1 }))}
        >
          Decrement
        </button>
        <p>{posCount}</p>
        <p>{negCount}</p>
      </div>
    );
  }
}

In the code above, we have the posCount and negCount states. Then we have 2 event handlers to set the state of posCount and negCount respectively. Then we display them in the p tags.

Since we destructured this.state in the render method’s first line, we can access them without referencing this.state in every line, saving us lots of typing and making the code a lot cleaner.

Conclusion

We can toggle components with a ternary expression if we want to toggle between 2 components. If we want to toggle one component on and off, we can use the && operator.

Also, we should destructure our props and states so that we don’t have to reference props , this.props or this.state all the time and make our code cleaner and we also can type less.

Categories
React Tips

React Tips — Modern Structures and State Updates

React is the most used front end library for building modern, interactive front end web apps. It can also be used to build mobile apps. In this article, we’ll look at some tips and tricks to make building apps with React easier.

Reduce the Use of Class Components

Class components have issues like dealing with lifecycle hooks and making sure the value of this is the correct one.

With the introduction of React hooks, function components are now smart. Therefore, we can use function components like we did we with class components, but without the headache of this and lifecycle hooks.

For instance, we can easily create a component that loads something from an API with the useEffect hook as follows:

import React from "react";

export default function App() {
  const [name, setName] = React.useState({});
  const getName = async () => {
    const res = await fetch("https://api.agify.io?name=michael");
    setName(await res.json());
  };
  React.useEffect(() => getName(), []);
  return <div className="App">{name.name}</div>;
}

In the code above, we have the React.useEffect call to call an API to get some data on load. We set the data with the setName function that’s returned from React.useState , which returns a state variable and a function to set the state.

Then we display it in the div that we returned.

To do the same thing with class-based components, we’ve to write the following:

import React from "react";

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {};
  }

  async componentDidMount() {
    const res = await fetch("https://api.agify.io?name=michael");
    this.setState({ name: await res.json() });
  }

  render() {
    return <div className="App">{this.state.name.name}</div>;
  }
}

As we can see, it’s a bit longer. Also, we have to extend the React.Component class to create a class component.

Also, we have to initialize this.state in the constructor and also call super .

In the componentDidMount hook, which is the same as using useEffect with an empty array as the second argument, we call the code to load the data that we want from the API.

Then we render the data in the render method with the div as we did before, except that we’ve to reference this.state to do that.

As we can see, the function component version is shorter. Also, we can use hooks however we see fit, unlike component lifecycle methods, which only run in certain parts of the lifecycle.

For instance, we can change the useEffect hook to watch for input value changes and call the API as follows:

import React from "react";

export default function App() {
  const [name, setName] = React.useState("");
  const [result, setResult] = React.useState({});
  const getName = async () => {
    const res = await fetch(`https://api.agify.io?name=${name}`);
    setResult(await res.json());
  };
  React.useEffect(() => {
    getName();
    return () => {};
  }, [name]);

  return (
    <div className="App">
      <input onChange={e => setName(e.target.value)} />
      <p>{result.name}</p>
    </div>
  );
}

In the code above, we used the useEffect hook to watch for the change of the value of name by passing name into the array of useEffect as the second argument.

The return statement in the useEffect callback is for running any cleanup code if needed.

We then call getName in a similar way as before, except that we interpolated name in the URL. As we can see, the useEffect hook does a lot more than a single lifecycle method in React can do. We did all that without having to reference this , which is also great since it’s always confusing.

This is one more reason to use function components with hooks.

Don’t use Props in Initial State

We shouldn’t use props in the initial state because the constructor is called only once when the component is created.

This means that when we make some changes to props next time, the component state won’t be updated.

The better way to reference props is to do it in componentDidUpdate . It’s a lifecycle method that lets us update the component when something change, such as when props change.

For instance, we can call this.setState in componentDidUpdate as follows:

import React from "react";

class Count extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0
    };
  }
  componentDidUpdate(prevProps) {
    if (this.props.count !== prevProps.count) {
      this.setState({ count: this.props.count * 2 });
    }
  }
  render() {
    return <div>{this.state.count}</div>;
  }
}

export default function App() {
  const [count, setCount] = React.useState(0);
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <Count count={count} />
    </div>
  );
}

In the code above, we check if prevProps.count ‘s value is different from this.props.count ‘s the value before calling this.setState so that we don’t call it repeatedly and unstoppably. Then we render this.state.count that we set in the render method.

This is the right because we’re updating the state according to the value of the prop. We should get the count displaying the count prop passed in App multiplied by 2.

If it’s in the constructor, then this.state.count won’t update because it won’t update when the props change as we have in our example.

Conclusion

With the introduction of hooks, it’s time to embrace function components and hooks together to create stateful components. It reduces the headaches with dealing with lifecycle methods and the value of this .

Also, if we’re using class components, then we have to remember not to set props as the value of a state property in the constructor, because the prop will never update the state after the first time the component loads. Instead, we should call setState in componentDidUpdate to update the state with our prop value.

Categories
React Tips

React Tips — Input Focus and Choices Controls

React is the most used front end library for building modern, interactive front end web apps. It can also be used to build mobile apps.

In this article, we’ll look at how to focus inputs and binding values of checkboxes and radio buttons to states.

Set Focus On Input After Render

To focus an input, we have to use the native DOM element focus method to do it. The method is available to input elements so we can call it.

We can use the useEffect hook to run something when the component renders. If we pass in an empty array as the 2nd argument, then the callback we pass into useEffect only runs when the component first loads.

For instance, we can write the following to do that:

import React from "react";

export default function App() {
  const input = React.createRef();
  React.useEffect(() => input.current.focus(), []);
  return (
    <div className="App">
      <input ref={input} />
    </div>
  );
}

In the code above, we have the useEffect hook and the input ref created with the createRef method, which passed into the ref prop of the input.

Then in the useEffect callback, we call input.current.focus() to call the focus method of our input element.

In the end, when we load the page, we’ll see that the input is focused when App loads as we desired.

Checkbox

To create checkboxes, we have to set the checkbox value as the value of the checked prop. Then onChange handler will take the checked value and then set it to the state we passed in as the value of the checked prop.

For instance, we can write the following to do that:

import React from "react";

export default function App() {
  const [selected, setSelected] = React.useState({});
  const handleInputChange = e => {
    const { name, checked } = e.target;
    setSelected(selected => ({
      ...selected,
      [name]: checked
    }));
  };
  return (
    <div className="App">
      <form>
        <label>
          apple:
          <input
            name="apple"
            type="checkbox"
            checked={selected.apple || false}
            onChange={handleInputChange}
          />
        </label>
        <label>
          orange:
          <input
            name="orange"
            type="checkbox"
            checked={selected.orange || false}
            onChange={handleInputChange}
          />
        </label>
        <label>
          grape:
          <input
            name="grape"
            type="checkbox"
            checked={selected.grape || false}
            onChange={handleInputChange}
          />
        </label>
      </form>
      <p>
        {Object.keys(selected)
          .filter(k => selected[k])
          .join(", ")}
      </p>
    </div>
  );
}

Making checkboxes work properly is tricky. In our handleInputChange function, we have to make sure that name and value properties of e.target have to be accessed from a synchronous context, so it can’t be inside the callback that we pass into setSelected . If we don’t do that, we get a warning saying that ‘ This synthetic event is reused for performance reasons happening’

In the setSelected function, we spread the existing properties of selected , and then update the name and checked values from e.target into the returned object in the setSelected callback.

The name value is from the value of the name attribute of each checkbox.

To get rid of the ‘A component is changing an uncontrolled input of type text to be controlled error in ReactJS’ error, we have to set a default value for each checked prop. In the code above, we set them to false .

Radio Buttons

Radio buttons are similar to checkboxes, but only one radio button in a group can be checked at one time. For instance, we can write the following code to bind the radio button’s checked value to a state as follows:

import React from "react";

export default function App() {
  const [selected, setSelected] = React.useState("");
  const handleInputChange = e => {
    setSelected(e.target.value);
  };
  return (
    <div className="App">
      <form>
        <label>
          apple:
          <input
            name="fruit"
            type="radio"
            value="apple"
            checked={selected === "apple"}
            onChange={handleInputChange}
          />
        </label>
        <label>
          orange:
          <input
            name="fruit"
            type="radio"
            value="orange"
            checked={selected === "orange"}
            onChange={handleInputChange}
          />
        </label>
        <label>
          grape:
          <input
            name="fruit"
            type="radio"
            value="grape"
            checked={selected === "grape"}
            onChange={handleInputChange}
          />
        </label>
      </form>
      <p>{selected}</p>
    </div>
  );
}

In the code above, we have the checked prop which is set to the expression that checks if the selected value is set to given value in the value prop.

Then in the handleInputChange function, we can call setSelected by writing setSelected(e.target.value) since the radio button sets e.target.value is set to the value of the radio button.

Therefore, the selected value will be displayed when we click the radio button, and we also see the radio buttons change the selection as soon as we click the radio button.

The checked prop controls the rendering of which radio button is selected and the value displayed in the p tag is updated with the handleInputChange function.

Conclusion

Setting the values of checkboxes is tricky in React. We’ll get warnings in the console if we didn’t set a default value in the checked prop of the checkbox. We’ll also get warnings if we access e.target within the callback of our state change functions.

Radio buttons are easier to deal with in React since we just set the value as a string when we click a radio button.

Focusing inputs is easy since we can just attach a ref to an input and then call focus on it.

Categories
React Tips

React Tips — Input Data Binding

React is the most used front end library for building modern, interactive front end web apps. It can also be used to build mobile apps.

In this article, we’ll look at how to add various form controls to our React app and set the state to the value of the control.

Drop-Downs

Dropdowns is a common form input control element added to many apps. It’s the select element in HTML. In React, we have to set the value attribute of the select element to the value we selected in addition to adding the onChange handler to add a handler to get the selected value and set it as the state.

For instance, we write the following code to do that:

import React from "react";

export default function App() {
  const [fruit, setFruit] = React.useState("");
  return (
    <div className="App">
      <select value={fruit} onChange={e => setFruit(e.target.value)}>
        <option value="apple">apple</option>
        <option value="orange">orange</option>
        <option value="grape">grape</option>
      </select>
      <p>{fruit}</p>
    </div>
  );
}

In the code above, we have the select element, which has various options. The value prop is set to the fruit state, and we have a function that calls setFruit to update the value of fruit .

Then we have the value of fruit rendered inside the p element. The onChange handler will update fruit so that the selected value is displayed when we change the drop-down choice.

We can omit the value attribute’s value if the drop-down text and value are the same.

Multiple Select Values

A select element can also be used to select multiple values. Instead of a drop-down, it’ll be a box where we can press Ctrl-click to select multiple values.

We can get the multiple selected values and then set them to a state by retrieving the values with the selected property set to true .

For instance, we can write the following to do that:

import React from "react";

export default function App() {
  const [fruits, setFruits] = React.useState("");
  const handleChange = e => {
    const options = e.target.options;
    setFruits(
      [...options]
        .filter(o => o.selected)
        .map(o => o.value)
        .join(",")
    );
  };
  return (
    <div className="App">
      <select multiple onChange={handleChange}>
        <option>apple</option>
        <option>orange</option>
        <option>grape</option>
      </select>
      <p>{fruits}</p>
    </div>
  );
}

In the code above, we set the multiple prop of select to true to enable multiple-choice selections in our select element.

Then in our handleChange function, we spread the options array-like object, which has all the choices.

Next, we keep the ones that are selected in a new array by calling filter with a callback that returns the ones with selected set to true . Then we map those into an arrays by passing in a callback which returns the value property.

Then we call join to join the array of strings into one string.

Therefore, when we select one or more items from the multiple select box, we get the selected choices displayed separated by a comma.

Text Input

Like with the single select drop-down, we have to set the value prop to the state that holds the entered value and the onChange handler to the function which gets the inputted value and then set them to the state which is passed into the value prop.

For instance, we can write that as follows:

import React from "react";

export default function App() {
  const [fruit, setFruit] = React.useState("");
  return (
    <div className="App">
      <label>Favorite Fruit</label>
      <br />
      <input value={fruit} onChange={e => setFruit(e.target.value)} />
      <p>{fruit}</p>
    </div>
  );
}

In the code above, we have the input element. We pass in the fruit state to value . Therefore to update it with the inputted text, we have to call setFruit with e.target.value , which has the inputted value to update the fruit state.

The fruit state is then rendered in the p element. In the end, when we enter something in the text input, we’ll see the entered text displayed in the p element.

Conclusion

We can add select elements and bind the selected value to a state variable with the onChange handler. Then we set the value prop with the state that we updated.

To add a select box that let users choose multiple options, we can add a select element and set the multiple prop to true . Then in the onChange handler, we get the options with the e.target.options array-like object. To use array options on it, we convert it to an array by using the spread operator.

Then we can select the selected properties by keeping the ones with selected property set to true .

Binding the inputted value of the text input to a state is done similarly to the way that we bind to select elements. We have an onChange handler, which calls the state change function returned from useState to update the state with the inputted value.