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

A Simple ReactJS Form Example

In this tutorial, we will learn how to use forms in React.

In HTML, Form elements such as input, textarea, and select typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().

input tag

In React, A input set the value using {this.state.value} and change handle by onChange event.

<input type=”text” name=”name” value={this.state.value} onChange={this.handleChange} />

checkbox tag

In React, checkbox input is checked or unchecked handle by attribute checked. On check or uncheck the event called and set the value true if checked and false if unchecked.

<label>
      <input type=”checkbox” checked={this.state.isConfirm} onChange={this.handleInputChange} />Please check to confirm:
</label>

textarea tag

In React, A textarea uses a value attribute, so textarea element in React is slightly different from ordinary HTML.

<label>
   Comment :
   <textarea name=”comment” value={this.state.value} onChange={this.handleChange} />
</label>

select tag

In HTML, select input creates a drop-down list and make selected to show the value as selected for drop-down values. In React, instead of using selected attribute, it uses a value attribute on the root select tag.

<label>
   Pick your favorite flavor:
   <select name=”flavor” value={this.state.value} onChange={this.handleChange}>
         <option value=””>–Pick your favorite flavor–</option>
         <option value=”grapefruit”>Grapefruit</option>
         <option value=”lime”>Lime</option>
         <option value=”coconut”>Coconut</option>
         <option value=”mango”>Mango</option>
   </select>
</label>

file input tag

In React, An <input type=”file” /> is always an uncontrolled component because its value can only be set by a user, and not programmatically. You should use the File API to interact with the files.

<label>
   Document Upload
   <input type=”file” name=”fileUpload” onChange={this.fileHandler} />
</label>

ReactJS Form Example

In the following example, we will set an input value using state value = {this.state.data}. onChange allows to update the state whenever the input value changes. And When you submit the form we apply the onSubmit event and restrict page to reload using event.preventDefault();

import React, {Component} from ‘react’;
import ‘./App.css’
class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         isConfirm: false,
         fileUpload : ”
      };
      this.handleInputChange = this.handleInputChange.bind(this);
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
   }

   fileHandler = event => {
      this.setState({
      fileUpload : event.target.files[0]
      });
   }

   handleInputChange(event) {
      const target = event.target;
      const value = target.type === ‘checkbox’ ? target.checked : target.value;
      this.setState({
         isConfirm: value
      });
   }

   handleChange(event) {
      this.setState({[event.target.name]: event.target.value});
   }

   handleSubmit(event) {
      event.preventDefault();
      let htm = ‘<h2>O/p</h2>A name was submitted : <strong>’ + this.state.name +'</strong> <br/ >’+
‘A comment was submitted : <strong>’ + this.state.comment +'</strong> <br/ >’+
‘A Confirm selected : <strong>’ + this.state.isConfirm +'</strong> <br/ >’+
‘Your favorite flavor : <strong>’ + this.state.flavor +'</strong> <br/ >’+
‘Your file Upload : <strong>’ + this.state.fileUpload.name+'</strong>’;

      document.getElementById(‘dataSubmit’).innerHTML = htm;
   }

   render(){
      return (
      <div className=”App”>
      <form enctype=”multipart/form-data” method=”post” onSubmit={this.handleSubmit}>

      <div>
         <label>
            Name : <input type=”text” name=”name” value={this.state.value} onChange={this.handleChange} />
         </label>
      </div>

      <div>
         <label>
            Comment :
         <textarea name=”comment” value={this.state.value} onChange={this.handleChange} />
         </label>
      </div>

      <div>
         <label>
            <input type=”checkbox” checked={this.state.isConfirm} onChange={this.handleInputChange} />
      Please check to confirm:
         </label>
      </div>

      <div>
         <label>
            Pick your favorite flavor:
            <select name=”flavor” value={this.state.value} onChange={this.handleChange}>
               <option value=””>–Pick your favorite flavor–</option>
               <option value=”grapefruit”>Grapefruit</option>
               <option value=”lime”>Lime</option>
               <option value=”coconut”>Coconut</option>
               <option value=”mango”>Mango</option>
            </select>
         </label>
      </div>

      <div>
         <label>
            Document Upload
            <input type=”file” name=”fileUpload” onChange={this.fileHandler} />
         </label>
      </div>

      <input type=”submit” value=”Submit” />

      </form>
      <div id=”dataSubmit”></div>

      </div>
      );
      }
}
export default App;

Output

ReactJS Router – Navigation In React

To get started with React Router in a web app, you’ll need a React web app. If you need to create one, we recommend you try https://github.com/facebook/create-react-app ( create react app). It’s a popular tool that works really well with React Router.

You can install React Router from https://www.npmjs.com/package/react-router-dom with either npm or yarn. Since we’re building a web app, we’ll use react-router-dom in this guide.

What is React Router?

Components are the heart of React’s powerful, declarative programming model. React Router is a collection of navigational components that compose declarative with your application. Whether you want to have bookmarkable URLs for your web app or a compos-able way to navigate in React Native, React Router works wherever React is rendering–so take your pick!

Usage with React Router:

It allows you to build single page web applications (SPA) with navigation. React Router uses component structure to call components. React router also provide functionality like the refresh page and back to url.

Features :

Here’s a run-down of a few of the features we’re excited about:

• Smaller bundle. Current size of the Router dependency in a fully migrated app is around 3kb
• Built of composable parts. Simple apps don’t need everything.
• Smart path matching, no more messing around with the order of your routes or exact props
• Nested Route Configs (much like v3 and @reach/router)
• Relative Links, navigation, and routes
• Access route data with useParams() from anywhere below the route
• Access to location and navigate with useLocation() anywhere in the app.
• Route parameter validation
• Route matching on location state
• Automatic focus management on route transitions
• Concurrent/Suspense Ready

React not provide router by default. So need to install

You can also install the router from https://www.npmjs.com/package/react-router-dom with ether npm or yarn.

In Linux & Mac you can install the react router:
npm install –save react-router-dom
In window machine you can install the react router.
npm install react-router-dom
Using yarn
yarn add react-router-dom

After run this command lets confirm the installation success and dependencies is listed or not . Go to package.json and in dependencies list see the name “react-router-dom”: version

ex. “react-router-dom”: “^5.2.0”

Important Info

• BrowserRouter is the router implementation for HTML5 browsers (vs Native).
• Link is your replacement for anchor tags.
• NavLink is also replacement for anchor tags but it provide the one extra attributes name as activeClassName.
• Exact attributes match the exact url of browser with the url given in route
• Route is the conditionally shown component based on matching a path to a URL
• Switch returns only the first matching route rather than all matching routes

Basic Routing Example

In this example we have 2 “pages” handled by the router: a home page, an about page. As you click around on the different s, the router renders the matching .

Note: Behind the scenes a renders an with a real href, so people using the keyboard for navigation or screen readers will still be able to use this app.

If no link get in the route must render to page not found page so we add the code

Next, copy/paste either of the following examples into src/App.js.


import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function App() {
  return (
  <Router>
  <div>
  <ul>
    <li><Link to="/">Home</Link></li>
    <li><Link to="/about">About</Link></li>
    <li><Link to="/dashboard">Dashboard</Link></li>
  </ul>
  <hr />
  <Switch>
    <Route exact path="/"><Home /></Route>
    <Route path="/about"><About /></Route>
    <Route path="/dashboard"><Dashboard /></Route>
  </Switch>
  </div>
  </Router>
  );
}

function Home() {
  return (
  <div>
  <h2>Home</h2>
  </div>
   );
}

function About() {
  return (
   <div>
  <h2>About</h2>
  </div>
  );
}

function Dashboard() {
   return (
   <div>
   <h2>Dashboard</h2>
   </div>
   );
}

Passing parameter to url

Params are placeholders in the URL that begin with a colon, like the `:id` param defined in

<Route path="/:id" children={<Child />} /></p>

Example of passing parameter


import React from "react";
import {
  BrowserRouter as Router,
  Switch,
   Route,
   Link,
   useParams
} from "react-router-dom";

export default function ParamsExample() {
   return (
  <Router>
  <div>
    <h2>Accounts</h2>
    <ul>
      <li><Link to="/netflix">Netflix</Link></li>
      <li><Link to="/zillow-group">Zillow Group</Link></li>
      <li><Link to="/yahoo">Yahoo</Link></li>
      <li><Link to="/modus-create">Modus Create</Link></li>
    </ul>
    <Switch><Route path="/:id" children={<Child />} /></Switch>
  </div>
  </Router>
   );
}

function Child() {
// We can use the `useParams` hook here to access
// the dynamic pieces of the URL.
  let { id } = useParams();
   return (
   <div>
     <h3>ID: {id}</h3>
   </div>
  );
}

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.