I comparatively new to React environment .I have wrote a very basic component for bookmarking feature.
Basically clicking upon favourite icon,
it sends an ajax call > create a record in the db > on ajax success show a flash message "Page added to favourites."
Its a toggle button, so upon clicking on it again ,
it sends an ajax call > delete the record in the db > on ajax success i show a flash message "Page removed from favourites."
Here is the component i wrote which works perfectly. But what i do not like is, using the setTimeOut function to hide the flash message. I fell like there must be other way (may be css) to achieve the same in React way.
import React, {
PropTypes
} from 'react';
import {
Component
} from 'aplus-base';
import axios from 'axios';
const API = "http://localhost:3000/favourites/toggle"
const API2 = "http://localhost:3000/favourites/current_bookmark_status"
@Component
export default class Bookmark extends React.Component {
static styles = require('./bookmark.sass')
state = {
bookmarked: '',
message: "",
alert: false
}
componentDidMount() {
this.fetchData();
}
toggle() {
const querystring = require('querystring')
axios.post(API, querystring.stringify({
current_page_key: '/marketing'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(response => {
this.setState({
bookmarked: response.data.bookmarked,
alert: true
});
const message = response.data.bookmarked ? "Added to Favourites" : "Removed from Favourites"
this.setState({
message
})
setTimeout(() => {
this.setState({
alert: false
});
}, 2000);
})
}
fetchData = () => {
const querystring = require('querystring')
axios.post(API2, querystring.stringify({
current_page_key: '/marketing'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(response => {
this.setState({
bookmarked: response.data.bookmarked
});
})
}
render() {
return ( <
div >
<
i className = {
this.state.bookmarked ? "icon icon-bookmarked" : "icon icon-bookmark"
}
onClick = {
this.toggle.bind(this)
}
/> <
div styleName = {
`result ${this.state.alert ? "alert-shown": "alert-hidden"}`
} > {
this.state.message
} <
/div> <
/div>
)
}
}
.icon display: inline-block width: 30px height: 30px background: no-repeat center background-size: contain vertical-align: middle &.icon-bookmark background-image: url(../assets/bookmark.png) transition: all 1s linear &.icon-bookmarked background-image: url(../assets/bookmarked.png) transition: all 1s linear .result position: fixed top: 0 left: 40% width: 20% box-sizing: border-box padding: 4px text-align: center font-weight: bold .alert-shown opacity: 1;
transition: all 250ms linear;
.alert-hidden opacity: 0;
transition: all 250ms linear;
<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>