Reputation: 598
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
Reputation: 148
You did it right. If you wish to improve it, you can
loading
propertyUpvotes: 2