, , , , , , ,

/

October 2, 2018

React.js Tutorial : Components

Creating React Components

Components is base and essential part of React application development.
To create your React.js web application you need to install react app generator which is written in node.js and available though node package manager.

npm install -g create-react-app

or

npm i -g create-react-app

Now lets create an quick react app using create-react-app generator via terminal on mac or linux or command Prompt on windows

/>create-react-app hello-world-react

It shall look like this

Now run following commands

cd hello-world-react

  npm start

It will launch the react app on http://localhost:3000/ , as you make changes in source file those are reloaded in web-browser instantly.

Now lets create a HelloWorld.jsx file in source folder and add the following code

import React, { Component } from “react”;

class HelloWord extends Component{

render() {

return <h1>Hello Word Componenet</h1>;

}} export default HelloWord;

In your app.js or index.js you can import your component like

import HelloWorld from “./HelloWorld”;
//and  in render method add it
<HelloWorld />

Please check below codesandbox preview of the HelloWorldCode

Few this worth noticing are

  • It is important to import React in order to write JSX code
  • JSX syntax look similar to HTML
  • The above type of components are called class component and is defined in React.Component.
  • Any html component used in JSX will have same tag e.g <div/> <p/> etc
  • class in html is written as className in JSX rest all html attribute will be written in same format
  • for attributes with – like tab-index font-size etc will be converted to camelCase like tabIndex fontSize etc.

In next tutorial I will write about using style sheets in react.