React For Beginners #3 - Components and JSX

**Understanding React Components**

In this tutorial, we will explore the basics of creating and using React components. A key concept to understand is how to create a default app that can be exported from an index file.

By default, when you run `npm start` or `yarn start`, it assumes that your `index.js` file has a component named `App` as its default export. This means that if you don't specify the component name in your import statement, React will automatically use the default export. For example, if you have an index.js file with the following code:

```javascript

import React from 'react';

import App from './App';

export default App;

```

You can import and use the `App` component without specifying its name, like this:

```javascript

import React from 'react';

import App from './index.js';

function Main() {

return ;

}

function App() {

return React.createElement("div", null, "Hello World!");

}

```

This works because `index.js` is set as the default export of the module. However, if you wanted to use a different component name or import multiple components, you would need to specify it in your import statement.

For example, if you want to use a component named `Info` instead of `App`, you can do so by specifying its name:

```javascript

import React from 'react';

import Info from './Info';

function Main() {

return ;

}

```

Or, if you wanted to import multiple components, including the default export `App`, you could do so like this:

```javascript

import React from 'react';

import { App, Info } from './index.js';

function Main() {

return (

);

}

```

**Creating a Functional Component**

Let's create a functional component called `Info`. A functional component is a simple function that returns JSX.

Here's an example of what the `Info` component might look like:

```javascript

import React from 'react';

function Info() {

return (

{title}

{showTitle}

);

}

export default Info;

```

This component takes two props, `title` and `showTitle`, which are passed to it from its parent component. The component uses these props to render an `

` element with the title and a `

` element with the show title.

**Converting to a Class-Based Component**

Now that we have our functional component up and running, let's convert it to a class-based component using JavaScript classes.

Here's what our `Info` component might look like as a class-based component:

```javascript

import React from 'react';

class Info extends React.Component {

render() {

const { title, showTitle } = this.props;

return (

{title}

{showTitle}

);

}

}

export default Info;

```

This class-based component is similar to the functional component we created earlier. However, instead of using a function to render JSX, we use the `render()` method.

**Using Auto-Formatters**

To format our code with auto-formatters, we can install an extension called Prettier in Visual Studio Code (VS Code). To do this, open the Extensions pane in VS Code and search for "Prettier".

Once you find the Prettier extension, click the Install button to install it. This will add the Prettier extension to your VS Code editor.

To format our code with auto-formatters, press `Ctrl + Shift + P` (Windows/Linux) or `Cmd + Shift + P` (Mac) to open the Command Palette. Type "Format Document" and select the option from the dropdown list. Alternatively, you can also configure VS Code to automatically format your code on save by going to Settings > Editor > Format.

**Performance Differences between Functional and Class-Based Components**

While both functional and class-based components are used in React development, there is a performance difference between them.

Class-based components are generally slower than functional components because they require more overhead to create an instance of the component. This is due to the fact that class components need to maintain state and lifecycle methods, which can be computationally expensive.

On the other hand, functional components are generally faster because they don't have the overhead of creating an instance of the component. Instead, they use the `React.createElement` method to render JSX, which is optimized for performance.

However, if you're dealing with a large number of state changes or complex lifecycle methods, class-based components might be a better choice. React recommends using functional components unless you have a specific reason to use class-based components.

In conclusion, in this tutorial, we explored the basics of creating and using React components, including functional components and class-based components. We also discussed how to format our code with auto-formatters using Prettier and how performance differs between functional and class-based components.

"WEBVTTKind: captionsLanguage: enhello everybody and welcome to the third video in this react tutorial for beginners in this video i'm going to be covering components and jsx so let's go ahead and dive in so the first thing we need to discuss is what a component is well component is really an aspect of your user interface now components in react are reusable this is one of the reasons why people love react because you have these really nice kind of streamlined uh components that are flexible dynamic and are reusable in many different areas of your application there's actually an entire component library or sorry entire component libraries that are built by people that contain just nice components that look nice on the screen have some good functionality and that you can use with your react application for example if you ever went and worked at you know shopify or spotify or facebook or whatever some place where they use react you would see that they probably have their own component library of all these different reusable components and you can use those to build different parts of whatever new user interface it is that you're going to go ahead and build regardless how do we create a component what does a component look like let's go through all of that so here i'm in my app.js file and this is our first component if you hover over this here you can see it's a jsx element that's what it returns and whenever you have something returning a jsx element in react by default that's going to be known as a functional component now there's two ways to create components one way is using functions like this another way is using classes i will show you the class way in a minute regardless since we are returning a div here inside the div we have some content whatever this is considered a component however if i go ahead and make a function and i say function and we just call this you know foo this is not a component i could return some string hello and this would work just like any other normal function would work uh this is not a component because well i'm not returning a jsx element which is uh this kind of div here we'll get into jsx at the end because there's some special syntax that i can show you but for now kind of assume that jsx is just your vanilla html with a few additions all right so anyways let me show you how we can make our own component and then hopefully this will kind of illustrate how they work so i'm going to say function and let's just make a let's say info component these are all going to be kind of silly examples for now just to illustrate what a component actually is now from this component what i'm going to do is return and actually i will return in parentheses here a div and then what i will do is have an h1 tag inside of this div so i'll say h1 and the h1 tab and i will say inventory system whatever okay and then after this i'm going to put a p tag here and for the p tag i am going to say um manage your stuff okay really straightforward we don't need to do anything much more than that now we have created an info component now just note here that whenever you are trying to return kind of html or jsx from a component it needs to have one parent element so here if i remove this div and i try to just return my h1 mip we're going to get an issue the reason for this is these are two separate components uh they're not one so now if i do the div i'm kind of returning this one div component if you want to call it that uh that has two children inside of it so i'm kind of wrapping the two children so that this actually works so just keep that in mind if you're getting errors with that make sure you have kind of one top level or parent element for all of the stuff that's being returned all right so now i'll show you how we use this info component so if i go inside of app now what i can do is i can actually just render info like that this is how you use a component you just write out the name of it put it in angle brackets and then close the component like that you also can just do it like that with a slash you don't need to have two separate tags and so now you can see we get inventory management or inventory system and it says manage your stuff now the great thing about components is you can use them multiple times right so i can just put another one here and then shows up again and then i can put another one and it shows up again i'm going to show you how we can make it so when we use a component multiple times we can pass different properties to it that'll be in the next video so that it looks different based on kind of the arguments that we give it anyways for now we'll leave just this kind of one info component like this and there you go you have now created your first react component now what i'm going to do is make another component and this component will kind of make like maybe an input field or something so we'll say function and we'll say maybe add item whatever you can call them whatever you want obviously and from here what i'm going to do is return an input field so i will return a div and then inside of this div what i'm going to do is make an input i'm going to say type equals and this will be button or actually let's make it text and i think that's pretty much all we really need for that and then what we can do is what is it saying here uh oh sorry the input tag doesn't have an ending tag it just ends like that and then is there a value we can give it a default value or we can give it um so actually what i'm going to do here is change this div to be a form so let's make this a form instead so i can use my label tag so let's remove form let's now give this an id let's say id is equal to i don't know input or input's probably not going to be a good thing to make it uh let's just make this text text form okay and then we can do a label so i'll say label for equals and then a text hyphen form and then inside of here we will say type something like that all right so now we've created our ad item component now i'm going to use that inside of my app so now after info i'm going to say add item like that now actually let's just end it this way and now notice we have our type something we can type something in here that's all working and if i wanted to use this multiple times well i could do that right and there you go now if we wait we should see that we have three input fields popping up that i'll say type something then of course inside of our components we could render other components so inside of our add item what we could do is maybe we could render the info component right so we could say info like that then if we run this notice that every single time that we generate an add item component it's going to also render an info component and start showing up afterwards all right so now that we've seen how to render the add item three times onto the screen we've looked at some basics of components i'm going to talk to you about jsx now jsx stands for javascript xml and there's a few different things that you can do with it but the most valuable is being able to evaluate javascript expressions right inside of your kind of output html here this makes it really really useful to generate dynamic pages especially if you have a ton of data that you want to render obviously you don't want to manually write all of that out you're going to want to write some code that can do it more efficiently for you so i'm going to go inside of my info component here and what i'm going to do is i'm going to define a variable so i'm going to say const and we'll just make this maybe title i'll set this equal to this is my title okay like that now i want to show the value of this variable inside of my html here how do i do that well you might be tempted just to write something like title right and you might think that that's going to work but when i do that you see that it just shows me the actual string title if i wanted to show the value of this variable not just the string title what i would do is surround this in single curly braces so when i do this notice now it's showing me this is my title because when i've surrounded in curly braces it tells react hey this is a variable this is an expression of some sort so you need to evaluate it and then display whatever the evaluation is and so in the same way i can take title and i can put that inside of my h1 tag here and now you're going to see that it says this is my title now we can do some other cool things as well i can make another variable here and i could say const show underscore or show title is equal to and then maybe we make this equal to false and now maybe we're only going to show the title and i'm typing in python right now it needs to be lowercase we're only going to show the title if show title is equal to true now what i can do is i could say all right show title question mark title otherwise nothing now if i do this notice that when show title is equal to false nothing's showing up but if i make this equal to true then you're going to see that if i type true with a lowercase i'm so used to the uppercase it shows my title so this right here is what's known as a ternary expression actually i believe that's what it's called i always butcher the name someone can correct me in the comments if i'm mispronouncing that but what this allows you to do is write a condition and then you put question mark and this says okay i'm going to check if this is true if this is true do this otherwise do this and so we're evaluating this expression and what we see is that we're going to get title whenever this is true and we're going to get an empty string whenever this is false now i could change this to say no title and then if i make this to false you see that it goes to no title so just an example of something interesting that you can do inside of jsx now sometimes you actually want to return completely different stuff based on the value of a variable or based on some condition in that case you could do an if statement inside of this function right and i can say if and this isn't jsx this is just vanilla javascript but i can say if show title then i'm going to do this and maybe we'll just go here and say title otherwise though what i'm going to do is return something else and maybe i'm just going to return a p tag and say you know empty okay so now if i do this and i save notice it's showing me empty because show title's false but if i change show title to true then it's going to show me this is my title and manage your stuff so just showing you kind of how you can dynamically render different things here you can use these uh single curly braces to embed an expression and the expression can be like whatever you want right like i could do something like let's go inside of here and go 2 plus 4. if i do 2 plus 4 notice we're going to get 6 right so we'll evaluate the expression and you also can do stuff like map filter you can use all kinds of different javascript functions inside of here and we'll see more and more of this as we go through this tutorial but that is the basics of kind of embedding variables or values inside of your output html here so we will continue in one second we need to quickly thank the sponsor of this video and this series which is algo expert as you know algo expert is the best platform to use when preparing for your software engineering coding interviews i actually work at algo expert as an algorithms instructor and you can find right now about 45 to 50 questions that were created by me on the platform check them out from the link in the description and use the code tech with tim for a discount on the algo expert platform now another thing to note here is how you use this kind of syntax i guess when you want this to be an argument to one of your components or one of the kind of html tags so for example maybe we want the four or maybe we want something related to let's let's go for input and let's say value maybe we want this to be equal to a variable we have maybe we have const value is equal to default or something like that and we want the value of this variable to be the value of this input box well in this case what you would do is the same thing you would just say value is equal to and then inside of these curly braces you would put value and now notice it's going to be equal to default if i change this and i say tim is great and we save notice it's going to give us tim is great now for the value so just another way that you can do that you can use the curly braces here okay so i think that was probably a good introduction to components and jsx syntax so using these kind of individual curly braces here and how it evaluates the expression the last thing i'm going to show you here is how we can create a class based component and how we can put these into different files because oftentimes we want to do that so in fact what i'm going to do is copy this info component right here you'll notice we'll get an error right now because we're trying to use info and while it's not defined what i'm going to do though is put it inside of its own file so i'm going to go to src i'm going to make a new file i'm going to call it info.js and then inside of here i'm just going to paste this now what i'm going to try to do is import this info function here from app.js now what you would do normally is you would say import and then you do the name of the component you want to import so info and then from and then dot slash and then info.js the reason you're doing dot slash is you're defining a relative path what that means is you're saying okay relative from where i am currently i want to look for info.js if you wanted to look in the public folder then you would have to type in obviously a different path then just dot slash info.js regardless you can see this isn't working it's saying attempting to import info.js does not contain default export and the reason for that is that when you are trying to import something from a function it must be export so what you can say here is right on the same line as the function export default function info and now this should work notice that everything is all good because we're exporting this function which means it's now allowed to be imported from here now if i didn't export this with default and i just said export what this will mean is i now need to surround info in these kind of curly parentheses here curly brackets and the reason for that this should work now um what's going on here unexpected token comma okay so i don't know why i was getting that error i just refreshed and everything's working now but regardless you can see that when i don't export this as the default export i need to surround it in parentheses or in these curly braces so when you exported default what that means is you can import it without these curly braces but when you do not export it default you just export it that means that you then need to surround it in these things right here and you can only have one default export so you say x4 default this is the default thing being exported but you can have as many other things being exported that are not the default if that makes sense so anyways we'll leave it as export default but what you can actually do is rather than writing it on the same line if you want to clean this up you can say export default and then info like that and now the same thing should work if we go over here and we run failed to compile i cannot import oh that's because we still have it in the curly braces let's remove the curly braces now you can see that this is if i refresh here still working awesome so that is good and here you can see we were exporting default app that's the reason why from index.js we could just import app if it wasn't the default export we would need to surround it in our curly braces okay so that is how you put stuff in different files it's usually a good idea to put your components in different files just to keep things nice and clean although sometimes you might have some small components in the same file and you export all of them out okay so now the last thing i'm going to show us is just how we can actually convert this info component that is a functional component to a class based component won't take us very long i just want to show you what a class based component looks like so what i'm going to do is say class and i will name this info and then this is going to extend react dot component now since we're extending react what we need to do is import react so we're going to say import react from and then this is going to be in all lower cases react make sure you don't import it from react dom if you do that you're going to get an error you want to import it just from react now this is the default export and so that means we can import it this way if it wasn't we would need to surround it in our kind of curly braces anyways now this should be working what i'm going to do is define a render method and inside of this render method you're going to write what you want to be returned to render on the screen so by default the return statement from a functional component is just kind of this render method whereas when you create a class you need to define manually the render method and so i'm going to copy this right here and paste it inside of there and i'll just delete it from inside here so we know that we've already got that now what i'm going to do is save you can see my stuff's auto formatting i'm going to show you in one second how you can set up the auto formatter if yours isn't doing that and then what i'm going to do is just copy my two variables here so const title and const show title and i'm just going to paste them for now inside of this render method we could put them as class variables if we wanted to but for now it's fine we'll just put them inside of rend then what i'm going to do is delete this so delete info save and you should see that now everything is working the way that it was before so all i've done is just now made a class-based component you can see that it works the exact same as a functional component except we kind of have to write more so we say class info extends react.component we have to define a render method and then it's just like a little bit different syntax that's really the main differences between a functional and class-based component just a little bit of a different syntax there is some performance differences but for our purposes they're not really worth maybe talking about if you're getting into you know professional react development then you can make the argument you know which is better functional or class-based components i believe right now react is recommending using functional components unless you have a ton of state in which they are saying you should use class-based components anyways we'll talk about that later when we actually discuss state but with that that's going to wrap up the video okay so i realized i totally forgot to show you guys with the auto formatter so i'll do that quickly right now there's an extension called prettier this is a really popular extension it has 12.35 million downloads anyways to find it go to the extensions pane in vs code search prettier and install it now that should auto format the code for you however you may have to configure this so what you can do is press ctrl shift p what this will do is open up the command palette and then if you type format you'll see format document with you'll see file save without formatting all of these different options and what you can press format document with and then for me i have multiple formatters but for you you'll probably just have one you can press prettier and then it will automatically format the document that you're on now if you want to format when you save i believe that's a default behavior but you can go to the vs code settings so if you go to settings and then i think you could probably look at format and here you go see editor format on paste format on save you can check these boxes based on the behavior that you would like and here's the let you guys figure that out that is the auto formatter again it's an extension called prettier and with that that's going to end the video i hope you guys enjoyed if you did make sure to leave a like subscribe to the channel and i will see you in another one\n"