Using the SnackBar component

We have already implemented toast messages by using the react-toastify component. Material-UI provides a component, called SnackBar, that can be used to show the messages to the end user. To get a uniform outlook in our app, let's use that component for the messages.

We can now remove the react-toastify imports from the Carlist.js file and we can also remove the component by typing the following command to the terminal you are using:

npm remove react-toastify

To start using the Snackbar component, add the following import to the Carlist.js file:

import Snackbar from '@material-ui/core/Snackbar';

We need two new state values for the Snackbar, one for the message and one for the status. Add these two state values to the constructor. The status state is called open and it defines whether Snackbar is visible or not:

constructor(props) {
super(props);
this.state = { cars: [], open: false, message: ''};
}

Then, we add the Snackbar component to the render() method. The autoHideDuration prop defines the time in milliseconds to wait before onClose is called. To show Snackbar, we just have to set the open state value to true and set the message:

// Carlist.js render() method's return statement
return (
<div className="App">
<Grid container>
<Grid item>
<AddCar addCar={this.addCar} fetchCars={this.fetchCars}/>
</Grid>
<Grid item style={{padding: 20}}>
<CSVLink data={this.state.cars} separator=";">Export CSV</CSVLink>
</Grid>
</Grid>

<ReactTable data={this.state.cars} columns={columns}
filterable={true} pageSize={10}/>
<Snackbar
style = {{width: 300, color: 'green'}}
open={this.state.open} onClose={this.handleClose}
autoHideDuration={1500} message={this.state.message} />
</div>
);

Next, we have to implement the handleClose function, which is called in the onClose event. The function just sets the open state value to false:

handleClose = (event, reason) => {
this.setState({ open: false });
};

Then, we replace the toast messages with the setState() methods, which set the open value to true and the displayed text to the message state:

// Delete car
onDelClick = (link) => {
fetch(link, {method: 'DELETE'})
.then(res => {
this.setState({open: true, message: 'Car deleted'});
this.fetchCars();
})
.catch(err => {
this.setState({open: true, message: 'Error when deleting'});
console.error(err)
})
}

// Update car
updateCar(car, link) {
fetch(link,
{ method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(car)
})
.then( res =>
this.setState({open: true, message: 'Changes saved'})
)
.catch( err =>
this.setState({open: true, message: 'Error when saving'})
)
}

The following is the screenshot of the message using the Snackbar component:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.106.237