Categories
React Tips

React Tips — Bootstrap, APIs, and Remove Array Items

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Right Way to do an API Call in React

We can call an API within a method in a class component.

For instance, we can write:

class UserList extends React.Component {
  constructor(props) {
    super(props);
    this.state = { results: []};
  }

  componentDidMount() {
    this.getUserList();
  }

  getUserList() {
    fetch('https://randomuser.me/api/')
       .then(res => res.json());
       .then(({ results }) => this.setState({ results }));
  }

  render() {
    const persons = this.state.results.map((item, i) => (
      <div>
        <h1>{item.name.first}</h1>
        <span>{item.email}</span>
      </div>
    ));

    return (
      <div>
        <div>{persons}</div>
      </div>
    );
  }
}

We get the data in the getUserList method.

We used the Fetch API to get the data.

The results array is populated with the setState method in the last then callback.

To make it load when the component mounts, we call getUserList in the componentDidMount method.

In the render method, we map the state with by calling this.state.results.map .

And then we render the resulting list in the return statement.

We can also fetch data in a function component.

For instance, we can write:

const App= () => {
  const [users, setUsers] = React.useState([]);

  React.useEffect(() => {
    const fetchData = async () => {
      const res = await fetch('https://randomuser.me/api/')
      const { results } = await res.json();
      setUsers(results)
    }
    fetchData();
  }, []);

  return (
    <div>
      {results.map(r =>
        <div key={r.id}>{r.first.name}</div>
      )}
    </div>
  );
}

We put the API request code in the useEffect callback.

The empty array in the 2nd argument makes the callback load on mount only.

We call setUsers to set the users state.

Then we can map to components that are displayed.

The Correct Path for img on React

We always use relative paths for images.

For instance, we can write:

<img src={require('../logo.png')} alt="logo" />

or:

import logo from './logo.png';
img.src = logo;

In both examples, we import the image as a module and use them.

Include Bootstrap CSS and JavaScript in a React App

To include Bootstrap CSS and JavaScript in our app, we install the Bootstrap package.

To install it, we run:

npm install --save bootstrap@latest

Then we can import the CSS by writing:

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

or:

import 'bootstrap/dist/css/bootstrap.min.css';

To import the JavaScript files, we install jQuery and Popper along with Bootstrap by running:

npm install bootstrap jquery popper.js --save

Then we can import both the CSS and JavaScript by writing:

import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap.js';

Return Empty Content in React render Function

There are many ways to return nothin in a React render function.

We can write any of the following:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

with the return keyword.

We must write it out explicitly.

So we can write:

return <div />

in the render method or use return with any of the other expressions.

Removing Element from an Array in Component State

We can remove an element from an array in a component state by returning a new array without the value that we want to remove.

For instance, we can write:

removeItem(index) {
  this.setState({
    data: this.state.data.filter((_, i) => i !== index)
  });
}

within our class component.

We called filter to return an array that has the items except for the one with the given index .

And we called setState to set that as the new value of the data state.

To make sure that the new array is always derived from the current array, we can write:

removeItem(index) {
  this.setState((prevState) => ({
    data: prevState.data.filter((_, i) => i !== index)
  }));
}

We passed in a callback to setState instead and returned the same array as the previous example with the filter method.

The only difference is that the value is derived from the current value which is stored in prevState.data .

We can also use the spread operator and slice to do the same thing:

removeItem(index) {
  this.setState((prevState) => ({
    data: [...prevState.data.slice(0, index), ...prevState.data.slice(index + 1)]
  }))
}

We called slice to get the chunks of the array that we want to keep.

Then we spread them chunks with the spread operator.

Conclusion

We can call APIs in several ways within a React component.

Also, we can remove an element from an array state in several ways.

Bootstrap CSS and JavaScript can be included in a React app.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *