React allows developers to create large web-applications that use data that can change over time, without reloading the page.
It aims primarily to provide speed, simplicity and scalability.
React is flexible. You can create a separate project on react, or you can add it to an existing code base of any framework like Angular.
This will show the value of name. We can also call a method that returns a value in JSX.
class becomes className in JSX, and tabindex becomes tabIndex.
How to render your JSX element?
You can render your react element wherever in the DOM you want. Suppose we have div element in our index HTML file, like,
We’ll call this the root DOM node, because everything inside this will be managed by React DOM. We usually have single root DOM node, but if you’re using an exisiting code base, you may have multiple root DOM nodes.
To render your element, we have a render method or ReactDom that takes two parameters, JSX element and DOM element. JSX element gets rendered into the specified DOM element.
Note : Your JSX element must contain only one parent tag. If you want multiple HTML elements, you can wrap them into a div.
Now, you’re familiar with react elements, let’s move on to React components.
React Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
We will write our code in ES6. We have a render method that returns the JSX element. This JSX element renders wherever we use this component.
We can add another component into your existing component. For eg :
Here, when we render the ParentComponent, it will also render MyComponent, and MyComponent’s element i’e. “Hello World” will be rendered.
Let’s create a simple app to make things more clear.
To setup a basic react application, install the following dependency :
npm install -g create-react-app
Use this command to create a basic project:
create-react-app my-app // where my-app is your project name
This will create the project as well as install the required dependencies.
Go into the project directory and run your application :
It will host the application on 3000 port, and it will look something like this:
Let’s take a look at the flow.
In public/ we have index.html where we have a div with id “root”.
In src/index.js we are calling the render method and rendering a component called App in the root DOM node.
Let’s have a look at App component in src/App.js.
Here is all the JSX that is rendered.
You can edit the JSX and see the changes.
Let’s add a new Component called MyComponent. Create a file MyComponent.js and add the following code :
Import MyComponent in App.js :
import MyComponent from ‘./MyComponent’;
And replace the JSX element with :
Now, it should look like this:
To Continue learning react, here’s the next blog where we cover How data is handled between Components in React (State vs Props)