Reşit Körsu
Reşit Körsu

Reputation: 598

React loading animation on button element on http request

I want my button to add loading animation class on click and remove the class after the request completes. I am using bulma css and it has 'is-loading' class for loading animation.

I have achieved what I want with this code but I'm not sure if this is the 'react way' of doing this. Here is what i did:

class App extends React.Component {
  constructor () {
    super()
    this.state = {
      users: [],
      isLoading: false
    }
  }
  
  toggleLoading = () => {
    this.setState((prevState, props) => ({
      isLoading: !prevState.isLoading
    }))
  }
  
  getUsers = () => {
    this.toggleLoading()
    let url = 'https://jsonplaceholder.typicode.com/'
    fetch(url + 'users')
      .then((res) => res.json())
      .then((data) => {
        this.setState({ users: data })
        this.toggleLoading()
      })
  }

  render () {
    return (
      <div className='section'>
        <h1 className='title'>User List</h1>
        <Button className={ 'button is-primary' + (this.state.isLoading ? ' is-loading' : '') } action={ this.getUsers } title='Get Users' />
        <ul>
        {
          this.state.users.map((user) => <li className='subtitle'>{ user.name }</li>)
        }
        </ul>
      </div>
    )
  }
}

const Button = (props) => (
  <button 
    className={ props.className }
    onClick={ props.action }
    >
    { props.title }
  </button>
)

ReactDOM.render(<App/>, document.getElementById('root'))
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>

Upvotes: 3

Views: 4054

Answers (1)

ladjzero
ladjzero

Reputation: 148

You did it right. If you wish to improve it, you can

  1. create a new Button component that supports loading property
  2. use classnames to manage className
  3. use react-refetch to handle fetch loading status

Upvotes: 2

Related Questions