Props and state in ReactJS

What is reactJS props?

“props” is a special keyword in React, which stands for “properties” and is being used for passing data from one component to another. But the important part here is that data with props are being passed in a uni-directional flow, means it can’t modify by child component. Props data is available for read only to child component.

let’s see how to pass Props in function component

import React, {Component} from ‘react’;
import ‘./App.css’
class App extends Component {
 render(){
 return (<div className=”App”>
 <PropsFunction title=”Reactjs Props Example” author=”sisnolabs” />
 </div>);
 }
}
const PropsFunction = (props) => {
 return(<div>
 <h1>{props.title}</h1>by {props.author}
 </div>);
}
export default App;

 

let’s see how to pass Props in class component

import React,{Component} from ‘react’;
import ‘./App.css’
class App extends Component {
 render(){
 return (<div className=”App”>
  <PropsClass title=”Reactjs Props Example” author=”sisnolabs” />
 </div>);
 }
}
class PropsClass extends Component {
 render(){
 return(<div>
 <h1>{this.props.title} </h1>by {this.props.author}
 </div>)
 }
}
export default App;

 

Destructuring props

You can also access the props by creating the const inside the function, it is called destructuring props. Please see the below child function. Same like you used in class component but you must use the this.props in place of props.

const PropsFunction = props => {
const {title, author} = props
 return(<>
 <h1>{title}</h1>by {author}
 </>);
}

What is reactJS state

As we saw the props, which can’t be modified by the component. But state allowed component to manage it’s own data.

let’s see how to use state in class component

import React,{Component} from ‘react’;
import ‘./App.css’
class App extends Component {
 render(){
 return (<div className=”App”>
 <PropsClass />
 </div>);
 }
}
class PropsClass extends Component {
 constructor() {
 this.state = {
 title: ‘Reactjs State Example’,
 author: “Sisnolabs”
};
 }
 render() {
 return (<div>
 <p>{this.state.title}</p>
 <p>{this.state.author}</p>
 </div>);
 }
}
export default App;

In function component creating & accessing the state is different. You must use “useState” hook to create the object in function component.

Syntax : const [variable, callback_function] = useState(default_value);

let’s see how to use “useState” hook in function component

import React, {Component,  useState} from ‘react’;
import ‘./App.css’
class App extends Component {
 render(){
 return (<div className=”App”>
 <PropsFunction />
 </div>);
 }
}
const PropsFunction = () =>{
  const [count, setCount] = useState(0);
  return(<div>
  <button onClick={()=>setCount(count + 1)}>You Clicked {count} times</button>
  </div>)
}
export default App;

Difference between state and props

Props
  • Props are variables passed to the component from parent to child component.
  • Props can not be changed by child component.
  • Access the props in component:

    Props.propsName in function component
    this.props.propsName in class component

State
  • State manage inside the component.
  • Class have full permission to modify the state
  • Access the state in component:
    useState hook used to create the state in function component
    this.state used to create in class component

ReactJS Introduction, File Structure, CSS Implementation

Introduction

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. React makes it painless to create interactive UIs. React is a Component based App. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM.

React can also render on the server using Node and power mobile apps using React Native.

Installation

You’ll need to have Node >= 8.10 and npm >= 5.6 on your machine. You can install the react from this url https://reactjs.org/docs/create-a-new-react-app.html

Create Project

You can create the project using npx in any platform using following command.


npx create-react-app project-name
cd project-name
npm start

Hello World Example

Try this simple code example. Copy below code in app.js

import React from 'react';
function App() {
   return (
       <div> Hello World </div>
   );
}

File Structure

In React application, there are several files and folders in the root directory. Some of them are as follows:

node_modules: It contains all React dependencies or call libraries and script required for the project.

public: It holds the public assets of the application. It contains the index.html where React will mount the application by default on the < div id="root" >< /div > element.
public/index.html : It is the only html file in your project. The component going to change dynamically but this html file responsible to serve the all view.

src: It contains the App.css, App.js, App.test.js, index.css, index.js, and serviceWorker.js files. Here, the App.js file always responsible for displaying the output screen in React.

src/index.css: Apply style to body tag and logo
src/index.js: Specify the Root component which situated in index.html
src/app.css: css apply to app component
src/app.js: App component represent the view that display in index.html

package.json: It holds various metadata required for the project. It gives information to npm, which allows to identify the project as well as handle the projects dependencies.

README.md: It provides the documentation to read about React topics.

Styling and CSS

1. CSS Stylesheet

CSS classes are generally better for performance than inline styles. To add the css class, pass a string as the className property.

Create myStylesheet.css
.error { color : red }

To use above css, you must import this css file to code file, in our case app.js


import React from 'react';
import ‘./myStylesheet.css’

function App() {
  return (
    <div className=”error”>Error Div</div>
   );
}
export default App;

2. Inline Styling

The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes. For example:


import React from 'react';
function App() {
  const Error = {
    color : 'red'
  };
  return (
     <div style={Error}>Error Div</div>
  );
}
export default App;

3. CSS Modules Stylesheet

This project supports CSS Modules alongside regular style-sheets using the [name].module.css file naming convention. CSS Modules let you use the same CSS class name in different files without worrying about naming clashes.

Create one file appStyle.module.css
.success { color : ‘green’ }

Then in app.js file used the below code to access this success class


import React from 'react';
import styles from './appStyle.module.css';

function App() {
  return (
  <div className={styles.success}>Success Div</div>
  );
}
export default App;

You can also add the bootstrap classes inside the script, but you must install the bootstrap first in react.

Gzip compression – to make website load faster

Now a days Gzip compression become popular for speed up website. It compresses webpage upto 60% to 80%. We know about zipping a file to make them use less space, today web servers can also compress the content before sending it to your browsers. It lower the bandwidth requirements of your server and speed up your site.

 

How Gzip works? Click Here to watch video

 

If mod_deflate and mod_gzip modules is enable on server, Here is the code you should added to your .htaccess file.


< ifModule mod_gzip.c >
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
< / ifModule >

 

If the above code did not seem to work, do not afraid there is other way to do it, remove above code from your .htaccess file and add this code in .htaccess file.


< IfModule mod_deflate.c >

# Restrict compression to these MIME types
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/css

# Level of compression (Highest 9 – Lowest 1)
DeflateCompressionLevel 9

# Netscape 4.x has some problems.
BrowserMatch ^Mozilla/4 gzip-only-text/html

# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4.0[678] no-gzip

# MSIE masquerades as Netscape, but it is fine
BrowserMatch bMSI[E] !no-gzip !gzip-only-text/html

< IfModule mod_headers.c >
# Make sure proxies don’t deliver the wrong content
Header append Vary User-Agent env=!dont-vary

< /IfModule >
< /IfModule >

 

Some hosting provider disable mod_deflate and mod_gzip modules, so above code will not work for you. Here is the solution.

 

1) Create file called headers.php and add the following code, upload to public_html or htdocs folder.

< ? php
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$timestamp = filemtime(__FILE__);
header('Last-Modified: ' . $timestamp);
$expirestime = 60*60*24*30;
header("Pragma: public");
header("Cache-Control: maxage=".$expirestime);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expirestime) . ' GMT');
header('Vary: Accept-Encoding');
$pathinfo = pathinfo($_SERVER['SCRIPT_FILENAME']);
$fileextension = $pathinfo['extension'];
if ($fileextension == 'css') {
header('Content-type: text/css;
charset=utf-8');
}
if ($fileextension == 'js') {
header('Content-type: text/javascript;
charset=utf-8');
}
} ? >

 

2) Create another file and give the name php.ini and add following code in it.
zlib.output_compression=1
auto_prepend_file=[PATH OF headers.php FILE]

if zlib.output_compression=1 is not work try utput_handler=ob_gzhandler instead.
Now you need to upload copy of php.ini file in every folder containing files you want to compress.

 

3) Now add below code in your .htaccess file
AddType x-mapp-php5 .php .shtml .html .htm .txt .js .css
if you have php4 then add x-mapp-php4 instead x-mapp-php5
if x-mapp-ph Continue reading Gzip compression – to make website load faster