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>
  );
}

Upgrade Laravel 4.2 to 5.0 and above version

Laravel framework 5.1 and above versions support php7. Laravel 5.x has modified its application structure to make it more easy, robust and developer friendly. You can not directly upgrade Laravel 4.x to 5.1 or above versions. First you need to upgrade 4.x to 5.0 and then only you can upgrade Laravel to 5.1 or above version.

If you have application built in Lravel 4.x and you are looking to upgrade it to newest version of Laravel to get maximum advantages of this modern framework. Here are steps to upgrade.

  • Install Lravel 5.0 – Open terminal (for linux users), go to folder to where you want to install Laravel , then run below commandcomposer create-project laravel/laravel {directory} "~5.0.0" –prefer-dist

    or you can follow official installation documentation https://laravel.com/docs/5.0/installation

  • Remove vendor/compiled.php file
  • then run this command composer update from root folder of project
  • Open config/database.php and set correct database details
  • Move all files from old public folder (Lravel 4.x project files) to root folder of new installation (Lravel 5.0).
  • Correct path in index.php as below
    require __DIR__.'/bootstrap/autoload.php';
    $app = require_once __DIR__.'/bootstrap/app.php';
  • Correct path on bootstrap/autoload.php to
    require __DIR__.'/../vendor/autoload.php';
    $compiledPath = __DIR__.'/../vendor/compiled.php';
  • Copy and paste your old routes.php file into your new app/Http/routes.php.
  • Move all your controllers from app/Controllers into the app/Http/Controllers. add the app/Http/Controllers directory to the classmap directive of your composer.json file.
  • Create app/Models
    add “app/Models” to the classmap directive of your composer.json file.
  • Move your views from app/views to the new resources/views directory.
  • Move your language files from app/lang to the new resources/lang directory.
  • Move your tests from app/tests to the new tests directory.
  • Add “laravelcollective/html”: “~5.0” to your composer.json file’s require section.
  • Edit config/app.php and add this line to the ‘providers’ array:
    'Collective\Html\HtmlServiceProvider',
    for the 'aliases' array:
    'Form' => 'Collective\Html\FormFacade',
    'Html' => 'Collective\Html\HtmlFacade',
  • Pagination (changes in model/controller class files) Replace any calls to $paginator->links() with $paginator->render().

    Replace any calls to $paginator->getFrom() and $paginator->getTo() with $paginator->firstItem() and $paginator->lastItem() respectively.

    Remove the “get” prefix from calls to $paginator->getPerPage(), $paginator->getCurrentPage(), $paginator->getLastPage() and $paginator->getTotal() (e.g. $paginator->perPage()).

  • Run command at terminal
    composer update
  • Filters in route will not work. For that need to create Middleware class for after and before to work. Follow below tutorial to create middleware
    https://laravel.com/docs/master/middleware
  • We need to add below code on top of controller file, you will get coding error, below will help you to fix it.
    use DB
    So that we can use DB::table(‘Tablename’)

    For input data add on top of controller file
    use stdClass;
    use Input;

    to use model in controller add below code on the top of controller file:
    use App\Models\Category;

    To use segment() function
    Add Request $request in function parameter
    and replace
    Request::segment(4); with $request->segment(4);

    Replace View::make with view()->make

    Replace Config:: with config(‘constant.img’);

  • Admin authentication – changes in route .php
    in place of “before=>auth.admin” use “middleware=>auth.admin”
    and for middleware auth need to create Authmiddlewear class.

Now as we migrated project from laravel 4.x to 5.0 , It is ready to upgrade to 5.1 or above version.

To upgrade laravel 5.0 to 5.2

  • Update your composer.json file to point to laravel/framework 5.2.*.

    Add "illuminate/html": "5.2.*",
    "laravel/framework": "5.2.*",

    to require section of your composer.json file.

  • Add “symfony/dom-crawler”: “~3.0” and “symfony/css-selector”: “~3.0” to the require-dev section of your composer.json file.
  • Then in your config/app.php file, add this to your providers array:
    Collective\Html\HtmlServiceProvider::class
    and this to your aliases array:
    'Form' => Collective\Html\FormFacade::class,
    'Html' => Collective\Html\HtmlFacade::class,
  • Run composer update command at terminal

Thats it!

Update: also read Introduction to laravel 5.x application structure