Skip to content

Instantly share code, notes, and snippets.

@pratik14
Created October 31, 2017 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pratik14/bcb4901ec1c8eb494a89980a6be2a8c1 to your computer and use it in GitHub Desktop.
Save pratik14/bcb4901ec1c8eb494a89980a6be2a8c1 to your computer and use it in GitHub Desktop.
SImple React Redux Notification. Single notification at a time
import React, { PureComponent } from 'react';
import NotificationContainer from './../../containers/notificationContainer';
class App extends PureComponent {
render() {
return (
<div>
<h1>Home</h1>
<NotificationContainer />
</div>
);
}
}
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import store from './store';
import App from './components/app';
const root = document.getElementById('root');
ReactDOM.render(<App />, root);
import React, { PureComponent } from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import './notificationContainer.css';
class NotificationContainer extends PureComponent {
constructor(props) {
super(props);
this.state = {
notificationVisible: true,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.notification.text) {
this.setState({ notificationVisible: true });
}
}
componentDidUpdate(prevProps, prevState) {
if (this.refs.showingNotification) {
setTimeout(() => {
this.props.removeAlert();
this.setState({
notificationVisible: false,
});
}, 3000);
}
}
handleClick() {
this.props.removeAlert();
}
render() {
const { notification } = this.props;
if (notification.text) {
const className = `message ${this.state.notificationVisible ? 'notification-shown' : 'notification-hidden'}`;
return (
<div className={className} onClick={this.handleClick.bind(this)} ref="showingNotification">
<p>{notification.text}</p>
</div>
);
}
return null;
}
}
function mapStateToProps(state, ownProps) {
return {
notification: state.notificationReducer,
};
}
function mapDispatchToProps(dispatch) {
return {
removeAlert() {
dispatch({ type: actionType.REMOVE_ALERT });
},
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(NotificationContainer));
const notificationReducer = (state = {}, action) => {
switch (action.type) {
case 'ADD_ALERT':
return ({
text: action.text,
});
case 'REMOVE_ALERT':
return ({
text: '',
});
default:
return state;
}
};
export default notificationReducer;
import thunk from 'redux-thunk';
import { applyMiddleware, createStore, combineReducers } from 'redux';
import notificationReducer from './reducers/notificationReducer';
export default createStore(
combineReducers({
notificationReducer,
}),
applyMiddleware(thunk),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment