DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info on

React Tips — Clean Syntax

Subscribe to my email list now at http://jauyeung.net/subscribe/

Follow me on Twitter at https://twitter.com/AuMayeung

Many more articles at https://medium.com/@hohanga

Even more articles at http://thewebdev.info/

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>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

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 />}

Enter fullscreen mode Exit fullscreen mode

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>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

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>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

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>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

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>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

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.

The post React Tips — Clean Syntax appeared first on The Web Dev.

Top comments (0)