Django & React Tutorial #12 - React Default Props and Callbacks

The Library We Need: NPM Install and Material UI Lab

To start with, we need to install the necessary packages in our project. For this tutorial, we will be using npm (Node Package Manager) to install the required package. Make sure you are in the frontend folder of your project, as this is where npm will look for the installation files. Pressing enter should load the package, and it may take a second or two to complete.

Once the installation has finished, we need to import the Alert component from Material UI Lab. This can be done by adding the following line of code at the top of our JavaScript file:

```javascript

import { alert } from '@material-ui/lab';

```

Alternatively, we could import it using the squiggly braces method like this:

```javascript

import * as alert from '@material-ui/lab/alert';

```

However, since we only need to import the Alert component for this tutorial, we will use the conventional import statement. Now that we have imported the Alert component, we can move on to defining its properties.

To show an Alert component, we need to define a state variable and update it based on certain conditions. In this case, we want to display either a success message or an error message. Let's start by defining the state variable:

```javascript

this.state = {

successMessage: '',

errorMessage: ''

};

```

We then need to update this state variable based on whether a success message or an error message is present. We can do this using the following code:

```javascript

if (this.state.successMessage !== '') {

alert(

{this.state.successMessage}

,

'Success',

() => {

this.setState({ successMessage: '' });

}

);

} else if (this.state.errorMessage !== '') {

alert(

{this.state.errorMessage}

,

'Error',

() => {

this.setState({ errorMessage: '' });

}

);

}

```

In this code, we first check if the success message is not empty. If it's not empty, we display an Alert component with a severity of "success" and pass in the success message as its content. We also define a function that sets the `successMessage` state variable to an empty string when the Alert component is closed.

We then repeat this process for the error message, displaying an Alert component with a severity of "error" and passing in the error message as its content.

To make these Alerts look nicer, we can use Material UI's built-in styles. For example, we could add some padding and margin to the Alert components like so:

```javascript

{this.state.successMessage}

```

This will add some padding and margin to the text inside the Alert component, making it easier to read.

Now that we have defined our Alert components with success and error messages, we can integrate them into our React application. We'll start by creating a new file for our Alert component, let's call it `AlertComponent.js`. In this file, we will define our Alert component using the following code:

```javascript

import React from 'react';

import { alert } from '@material-ui/lab';

class AlertComponent extends React.Component {

constructor(props) {

super(props);

this.state = {

successMessage: '',

errorMessage: ''

};

}

render() {

if (this.state.successMessage !== '') {

return (

{this.state.successMessage}

);

} else if (this.state.errorMessage !== '') {

return (

{this.state.errorMessage}

);

}

return null;

}

}

export default AlertComponent;

```

This code defines a React component called `AlertComponent` that uses the Material UI Alert component. It also defines two state variables, `successMessage` and `errorMessage`, which are used to store the success or error message.

We can now import this component into our main application file and use it as needed. Let's go back to our previous code and replace the hardcoded alert messages with a call to our new AlertComponent:

```javascript

import React from 'react';

import ReactDOM from 'react-dom';

import './styles.css';

import App from './App';

ReactDOM.render(

,

document.getElementById('root')

);

```

And finally, let's create a new file for our main application component, `App.js`, and add the AlertComponent to it:

```javascript

import React from 'react';

import App from './App';

class App extends React.Component {

render() {

return (

);

}

}

export default App;

```

With these changes, we can now use our Alert component in our application. We've installed the necessary packages using npm and defined a reusable Alert component that can be used throughout our application.

Note: This is just an example of how to create a simple alert system using Material UI Lab. In a real-world application, you would likely want to add more features, such as the ability to customize the appearance of the alerts or to display multiple messages at once.

"WEBVTTKind: captionsLanguage: enhello everybody and welcome to video 12 in the django and react tutorial series now what we're going to be doing in this video is just continuing from where we left off in the last we're gonna be making it so that the settings page is actually proper and does what we want it to do now as i discussed what's involved with that is changing this title changing this create a room button title to be update room and then having this back button being removed so we're going to make the actual create a room component to be reusable and that's kind of the point of this this video i guess it's going to show you how we can make a component be used in multiple scenarios now i'll first just start by saying that once again this tutorial series is not following all the best practices all the industry standards this isn't something that you would probably see at you know like google or facebook like they would be doing things probably a lot different than the way i'm doing it right here the point of this series as i've said from the beginning is just to teach you how this stuff works to give you kind of a cool fun project to work on and this is exactly what i would do if i was just kind of building a hobby project i didn't really care a ton about the code quality and i just wanted to learn a new framework and kind of learn a backend thing like django as well and just see how they work and get some experience with it so keep that in mind you guys are welcome to be as critical as you want as the coding here but as i've said many times it's not meant to be industry standard and all of that so anyways let's continue so let's go to the create room page and actually before i do that let's kind of get a better introduction into this so if we have a look at render settings here which is what we did in the last video you can see we're calling create a room or we're using the create room page component now we pass all this information through right we pass the votes to skip this is stored in this current state of the room page we pass the guest can pause again stored in the state we pass the room code this dot room code is defined in the constructor so this dot room code is equal to this dot props dot match dot params.room code and then we pass this update true so that we know what we need to do in the create room page whether it's going to be creating or updating or whatever we also pass a callback that we should be calling whenever the room actually updates so we'll use that later but that's the information we're passing through so now what i want to do is in the create room page i want to take these props and actually use them right so here you can see that by default we have this dot state is equal to you know guess can pause we have votes to skip is equal to this.defaultvotes but i don't want it to be equal to these hard-coded values i want it to be equal to what we pass in through the props but the issue is that we're not always passing this information through through the props right if i go to home page and we have a look at create room page we're not passing any information through the props so we need a way to set the default value for the props right and again those props are just the piece of information we're passing in so this is where we're actually going to use something which is called default props we're going to define what the default value for our property should be so there's multiple ways to do this but this is the easiest way in my opinion we're going to define a static variable and it's going to be called default props and then it's going to be equal to the name of all of the props that we expect to be passed in as well as their value so what we're going to say is votes to skip and then we're going to set this equal to whatever we want the default to be which is 2 right then next we're going to say guest can pause this is going to be equal to whatever we want the default to be which is in this case true then we need update update the default for this i'm going to say is false then we need the room code the update for this i'm just going to say is null or sorry the update the default for this i'm going to say is null and then we need the update callback so i'm going to say update callback and that's going to be equal to just a default arrow function all right so that's all we need for our default props and pretty much this means if we don't pass any of these props through if any of the ones that are in here are not passed by default they will have these values just like a default parameter in python or some other languages all right so now that we have that let's actually start using them so inside of the state now rather than having the state be equal to true and this dot default votes which i just deleted we're going to say guess can pause is equal to this dot props dot guest can pause because that's the information we're passing through to the create room page same thing for default votes it's going to be this dot props dot votes to skip that way this state will be at whatever we pass through and by default it will be true and it will be 2. all right so now that we have that let's go change anywhere else in this code that was using hard-coded values like 2 or whatever else we may have had so if we go to right here inside of the text field this text field just a reminder is the votes required to skip the song you can see we're using this dot default votes we don't want that we want to change this to this dot state dot and votes to skip so this way this will get updated based on the state or the default value will be equal to whatever the state is right and that's what we need for that all right now that we have that let's see if there's anything else that's hard coded doesn't look like there is so before we continue i need to quickly thank the sponsor of this video and this series which is algo expert algo expert is the best platform to use to prepare for your software engineering coding interviews has over 110 coding interview questions and has great instructors on the platform like myself if you want to get better at data structures and algorithms and prepare to ace your software engineering coding interviews then check out algo expert from the link in the description and use the code tech with tim for a discount on the platform so now let's start doing what we were discussing and changing say like the label of this from create a room to update a room in the specific scenario so the first thing i'm going to do is inside of render i'm going to define a variable here i'm going to say const we'll just say title and this is going to be equal to the following condition so i'm going to say pretty much if this dot props dot update so if that is true then the title should be equal to update room otherwise it's going to be equal to create a room like that so now where i have create a room all i have to do is replace this with title and now we'll perform this logic we'll see if we actually are in the update state or if we're in the create state so if update's false it will be create a room and then this will automatically change the title for us pretty straightforward and well pretty easy to do so in fact let's just test this out before we go too far make sure we haven't made any mistakes yet let me refresh this let's go to settings and notice already it changes to update room so the next thing we want to do is we want to remove this create a room button and this back button or we want to change them right so they look a little bit different so this is a little bit more complex to do but still not super difficult we're going to do a very similar thing to what we did in the previous component where we kind of have multiple options and then we render each of them so the first thing i'm going to do is i'm going to steal this or not steel but you know copy this these two grid items right here so the create a room button and the back button i'm going to copy both of those and i'm going to put them into their own method so i'm just going to go here i'm going to call this one render create buttons now the reason i'm calling it this is because we're going to have two methods one that renders the buttons to create a new room and one that renders the buttons to update a rip so inside of here what we'll do is we'll return all of this code we will have to make a modification but we will return this now notice that this isn't working right it's giving me all these red highlights that's because all of this is not contained in one upper level parent right it says jsx expressions must have one parent element so all i have to do is wrap this in a grid container so i'm going to say grid container like that i'm going to say the spacing is equal to one and then i'm just going to close the grid so we'll take that closing tag and put it at the very end save and then we're all good so some of you may be saying well you're going to have a grid container inside of another grid container right because what i'm going to do is i'm going to render that at the bottom of this grid you'll see in a second it's hard to go through everything until the code's actually on the page but pretty much it's totally fine we're just going to render this grid inside of this grid here and nothing's going to look any different it's totally okay we can definitely do that so now we have render create buttons that's good and now what we want to do is we want to say render update buttons so pretty much changing what buttons we're going to be using based on we're updating or we're creating so for this one it's really straightforward i don't want the back button right i just want a button that says update room so all i'll do is just copy the grid item here for create a room and just return it from here so i'll return grid it can just be a regular grid item since there's only one element it's not two grid items like we had here i'll change create a room to say update room and then we'll change this on press method to be something that actually is going to call the right endpoint uh but for now we'll leave it at this just because we don't have another thing to put here right now so anyways now we have render create buttons and we have render update buttons or we could say render update button i mean just to keep it simple we'll keep them both at plural and now let's go to the bottom of our grid let's go inside of here where these buttons were before and let's just write another condition so let's say this dot state dot update question mark so if we are updating then let's return this dot render update buttons otherwise let's return this dot render create buttons there we go so this way we'll show one of the two depending on what our update state is now sorry this should not be state i don't think i'm pretty sure this should be props this dot props dot update i think that is the correct one and yeah it is just checking in my other code here all right so now that we have that let's have a look at how this works uh so let's refresh let's go to settings and we're getting an error it's saying this dot render update button is not a function oh render update button i think that needs to be render update buttons let's see yeah it needs to be buttons with a plural my bad so i just forgot the s there all right let's refresh and there we go settings and now you can see it says update room update room and then we have our close button when we close it that works properly just to make sure this is still working uh in the other side or on the other side in the create room page let's leave the room let's press create a room and notice create a room looks exactly like it did before let's press the button boom creates room for us we are all good settings shows us a similar looking thing except it says update room all right so there we go the cosmetics are pretty much done now and what we need to do next now is make this settings button actually work right so when i press update room you can see we got this uncaught error whatever is happening here we need to make this do something different rather than having it create a room we need to make it update the root so what i'm going to do is make another method inside of here so notice we have the method for handle room button press now let's make a method for handle update button pressed so let's say handle update button oops pressed like that and then inside of here i'm literally just going to copy all of this and i'll just change this slightly to what we actually need so for update we need votes to skip we need guests can pause and we also need what we need the room code so i'm going to say code is equal to this dot props dot room code so there we go that should be all good we're going to change the method now from post to patch because what we're going to do here right is we're going to hit the endpoint we created in the last video let's just go there and have a look at it quickly which is update room now update room takes a patch request so we're going to send patch instead of post all right so let's head back to the create room page here we have the method as patch and then what we're fetching well we're not actually going to be fetching create room we're going to be fetching update rooms let's change that to be update room we'll send all of this information as we defined here and then we're just going to have to change what happens here so we don't want to redirect to room slash and then whatever the code is because we're already on that page so i'm going to remove this here and what i actually want to do is check and see if this was valid right so i want to see if we got an okay response and what i'm actually going to do is have a message pop up on the screen this will be kind of a nice like learning thing to show you how to uh put alerts on the screen uh they will say hey you know room was updated or room wasn't updated so we'll have an error message or we'll have a success message and then to get back to the other page they can simply just press that close button that we have so that'll be the last thing that we need to do this will take a few seconds to finish but anyways let's go ahead and try it so dot then we have a response and then what we want to check inside of here is if this response is okay so if response dot okay we want to do something otherwise we want to do something else now what i'm actually going to do is i'm going to add two things to the state here one that's going to store an error message and one that's going to store a success message now depending on if we have an error message or a success message we'll pop that up on the screen and we'll show the user hey you updated the room or hey that didn't work and then whatever the error message is uh so we'll actually we can do it in here and then we'll actually set the state uh above after we'll say this dot set state and then if response is okay then it's a success message so we'll say success msg add another s there is equal to and then what do we want to say we'd say room updated successfully exclamation point all right so that's what we'll do for the success message we can copy this and then we'll change success message to be error message and we'll just say error updating room error updating room dot dot dot uh now you could use whatever was actually returned here as the error message i'm not going to do that just because we don't really need to but anyways that's what you can do and what am i doing with an equal sign sorry this has to be a colon non-equal sign that was going to give us some issues so success message colon whatever it is error message colon and then whatever we want all right so now let's go to the top of our file in the constructor and we have to add the default state for error message and for success message so we'll say error message empty string and then success msg and that as well is an empty string all right so now what we have to do is we need to bind this handle update button press method so let's do that we'll bind it up here say this dot no not theme this dot handle update button pressed equals this dot handle update button pressed dot bind we need to bind that to this then we need to change what the on click event is for the render update button so if we go here and we see that we have the button for update room uh oh handle room button pressed yeah that needs to change this needs to be changed to this dot handle update button press so now we're going to actually call the correct method from the update button all right so that should be all good the next thing that i want to do is i want to make it so that we actually show those error messages right so we show some pop-ups saying hey this was successful or hey this wasn't successful now to do that we're going to need to import some new things here and we're actually going to have to install one new library so i can remove theme provider because that was a mistake i'm going to import something called collapse so i'm going to import collapse like that from and then at material ui core what collapse will allow us to do is show something or collapse it on the screen right so pretty straightforward but just lets it appear or disappear all right so now we're going to go inside of here and we're going to add a new grid item inside of here which will be used to store our messages so error message or success message so let's just copy one of those grid items now inside of here i'm going to make a collapse tag i'm going to say collapse like that we'll end the collapse and then there's a few things that we need so the first thing inside of collapse that we define is in now in is pretty much a boolean value that tells us whether or not this collapse should be shown or it should not be shown so if the condition that i put inside of these squiggly brackets is true we'll show whatever is inside of this collapse tag otherwise we won't show it so it's actually pretty useful but what we'll do is we'll just say this dot state dot error msg right does not equal and then we'll make a blank string or this dot state dot success message does not equal and we'll do an empty string this is just going to tell us if we actually have any message to show right so if we have an error message or we have a success message then we will show the collapse if we don't we're not going to show it then based on the message we have we're going to show a different alert so we're going to show a different like pop up on the screen one that's green if it's successful run one that's red if it's not but to default or to start here i'm just going to say this dot state dot success message just because we're probably not going to have an error message based on the way that we're doing this but i just want to put this here so you can see kind of what it looks like and how it pops up in the collapse window then we'll change it to look a little bit look a little bit nicer anyways let's refresh now let's go to settings and let's update the room and notice we get a little pop-up room updated successfully now let's see if this actually is the case if it's actually working so let's first like go and make a new room we'll make a new room we'll make the votes like 10 and we'll say no control so we create the room we can see that guest can pause is false votes is 10. let's press settings notice that we get 10 but this one isn't updating so update room didn't change it was on play pause but they should have said no control right so if you go back here it says guess compose is false if i go to settings it says play pause which isn't right so first of all we need to change this that's one bug but at least 10 is showing properly but anyways let's just update this so let's update it to 15 and play pause create room okay or sorry create room update room room updated successfully let's close this but now notice here it shows 10 and it shows false it's not showing the updated values but if i refresh this then we get 15 and then we get false now the reason that happened is because this component isn't being told to update right when i go to settings and i actually change this and then i come back here there's nothing that tells this component hey you have to update your values so we need a way to tell it to update its value so that's the next thing we'll have to do as well but anyways this is working just not as perfect as we'd like it to so let's fix that first bug which is that we aren't actually showing the proper value for guests can pause so guest control of playback state that's going to be somewhere here and there we go we say the default value is true the default value should not be true the default value should be equal to whatever we passed in from the prop right so inside of here we're going to say this not state this dot props dot and then guest can pause and then i actually need to put this dot to string the reason for that is that default value takes a string so we're just going to convert this boolean value to string so that all is good but let's try this out now and see if that's working so let's refresh we have false and we have 18 we go to settings and now you see it's showing the correct one okay so bug one has been fixed now we need to fix the next bug which is that when we press update room we actually want it to update over here so how do we do that well this is where we get into that callback function that i was talking about before so if i go to room.js notice that we have a callback we pretty much want to call this callback after we update the room so what should the callback function be we need a way to update the room so that it has the the correct state and it shows the correct values so really all we actually need to call is get room details right because this is what we did in a way earlier uh tutorial video but this updates the state to be equal to whatever the current values are for the room so all we do is we pass as the update callback this dot get room details reminder we don't call the function we just pass it in or the method whatever you want to call it and then inside of create room we need to call this callback so what i'm going to do is i'm going to go into the handle update button pressed and after all of this is done so after the dot then i'm going to call this callback function so i'm going to say this dot and then i guess what is it update callback like that and we'll simply call it but notice there might be a slight problem here because this fetch might not be finished executing before we call this because of the way that we have the dot then set up so what i really need to do is just at the bottom so i'm going to say this dot update callback inside of the dot then i'm just going to put it at the very bottom so that way we wait until we actually do the update message and this endpoint has actually been reached and called and we've got a response and then we call this.updatecallback so just kind of an important detail there want to make sure we do this after this is finished so we put it inside of the dot that all right so now that we have that what we need to do is simply make it so that we actually show the correct error messages and we'll see if this is working so let's before we show the error messages uh make sure this is working when refresh gonna go to settings let's change this to say 10 and play pause update room we go back and this hasn't updated and it's saying this.updatecallback is not a function okay so the reason why this isn't working and i just realized already is because i called this.updatecallback but it should be this.props.updatecallback because we pass this through the props we don't actually have a function defined called update callback inside of here so if we go to props we can see we have update callback so that's what we need to call it so let's try this now let's refresh let's go to settings let's just change this to six no control update go back and this hasn't happened again and it's saying this.setstate is not a function at room.jsline39 so let's have a look there room and line 39 oh right here so i guess the reason why this isn't working is because we haven't bound get room details uh to the actual this keyword so just to go through what happened here i pass get room details as the callback function to my create room page but since we didn't bind this callback function to this keyword of this class there's no this dot set state available when we call it from the other class hopefully it's clear so far but the solution to this whenever you see something like this.setstate isn't available is to simply bind this function or bind this method to the clasp and this keyword so all i have to do is say this getroomdetails equals this.getroomdetails dot bind to the this keyboard then i'm actually just gonna take uh this.getroom details the function call i have in my constructor and put it at the bottom uh just because that makes a bit more sense for uh to me to do but yeah okay so i think that should be good let's refresh now and have a look let's go to settings let's change this to 10 and go play pause true update room go back and notice this is updated we didn't have to refresh it just updated again to prove it to you i'll change it to 11 go back and see this is 11 we didn't have to refresh it's just there all right so that's good everything seems to be working now the last thing we need to do is make it so that these error messages or success messages look a little bit nicer so let's go ahead and do that so actually for this part right here what i need to do is use a new component that we actually need to install uh so right now we have a material ui installed but we don't have all of like the sub libraries of material ui installed and the component i want to use is called alert but it comes from the material ui lab component library so what i need to do is cd into my front end i'm just in a blank terminal here in bs code and then i'm going to use mpm to install the package that i need so npm install and then we're going to say at material if i spell it correctly hyphen ui and then slash lab like that so this is the library we need npm install app material ui lab make sure you're in the front end folder so you can access npm all right we're going to press enter give it a second to load here and install you should see that it added one package from one contributor it doesn't matter if it's the alpha or whatever it will still work and now what we're going to do is import alert from material ui lab so let's go to create room let's go to the top and let's go import alert like that from and then act material hyphen ui lab slash alert now we could import it uh just using the squiggly braces from material ui lab but since it's the only one that we need we'll just take it from the actual alert package itself or alert file itself all right so now we have alert and we're almost done this tutorial what we need to do now is show our alert so let's go into collapse and rather than just showing the success message we're going to show a specific alert based on if we have a success message or if we have an error message so the first thing that we'll do is we'll pretty much say this dot state dot success message does not equal empty and if it does not equal empty then we'll show something specific so we'll do the question mark and what we'll show is inside of parentheses and alert so we'll say alert like that uh we can end the tag um yeah and then inside of here we can say this.state.successmessage what this is saying is if we have a success message if it's not empty then show this alert that has the success message now in the other case we'll show another alert so i'll literally just copy this line and we will make these look a little bit nicer in a second and instead of success message we will show error message all right so the reason this works is because if we have a success message we're not going to have an error message if we have an error message we're not going to have a success message so we show one of the two based on if we have a success message or not now for the alert for the success message i want to define what type of alert this is so if we want the alert to be success then we say severity is equal to success like that it's going to make it green similarly for the error we can say severity is equal to error like that and then i also i also want us to be able to press a button to actually close this alert so to do that i need to add an on close like that i'm going to say on close is equal to i'm actually going to make an arrow function here so we'll say arrow like that then inside of this arrow function since i'm closing the alert and you'll see how this works once the alert comes up i'm going to set the state to clear the error message or clear the success message whatever one we're in so i'll just say this dot set state and then inside of here we'll say success message and we'll just make that equal to a blank string now i'm going to copy this and we'll do the exact same thing for error except instead of success message we're just going to say error message like that now i know this looks all complicated and fancy it's really not and also yeah i think we're all good here but pretty much all this is doing is it's going to show a little x icon on our alert when we add this on close prop here and then it's going to call this function which will just change the state when we press that x so by pressing the x button it will clear the success message state or it will clear the error message state and then that way will stop showing this collapsed content all right so hopefully that's clear but let's just refresh and have a look at how this works now so refresh settings update and we get room updated successfully has its nice default success icon when i press x it closes right now we can go and update room press x it closes i don't know why it's showing the error message for a second there that's actually interesting to me but let's update room closes and we're good now i will look into why it's showing that little like red error message after we update it because you can see it kind of goes red before it collapses all the way down but that's something that we can tackle in the next video so anyways that was all i wanted to show we're getting really close to integrating with uh spotify now in fact in the next video we'll probably start doing that because most of the ui stuff that i wanted to do is pretty much done at this point in time so anyways i hope you guys enjoyed if you did make sure you like subscribe to the channel and of course i will see you in another react and django tutorial\n"