Sunday, April 24, 2022

ReactJS Part 9 : Fetch API POST

 

import React, { useState } from 'react';

export function CreateGroup2(props) {
    const [nameValue, setNameValue] = useState("");
    const [detailsValue, setDetailsValue] = useState("");

    const createGroupData = async (event) => {
        event.preventDefault();
        let postData = {
            groupName: nameValue,
            description: detailsValue
        };
        let response = await fetch('api/groups', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(postData)
        });

    }

    return (
            <div>
                <form onSubmit={createGroupData}>
                     <div className="form-group">
                          <label htmlFor="name">Name</label>
                          <input
                                type="text"
                                className="form-control"
                                id="name"
                                onChange={(e) => setNameValue(e.target.value)} />
                     </div>
                     <div className="form-group">
                           <label htmlFor="description">Description</label>
                           <input
                               type="text"
                               className="form-control"                                    id="description"
                               onChange={(e) => setDetailsValue(e.target.value)} />
                     </div>
                     <button type="submit" className="btn btn-primary"  id="create-group">Submit</button>                   </form>

                </div>
    );
}


Saturday, April 23, 2022

ReactJS Part 8 .Net Core React - Connecting to Web API - Fetch API GET

The blog is a continuation of ReactJS Part 7 .Net Core React Project.

 In the blog Angular with .Net Core 3 and Visual Studio Code I have discussed creating Web API with .Net 5 CLI. 

.Net 5 Minimal API Progrm.cs

using corereact.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddScoped<ContactManagementContext>();
Scaffolded Web API Core Controller code.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using corereact2.Models;

namespace corereact2.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class GroupsController : ControllerBase
    {
        private readonly ContactManagementContext _context;

        public GroupsController(ContactManagementContext context)
        {
            _context = context;
        }

        // GET: api/Groups
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Group>>> GetGroups()
        {
            return await _context.Groups.ToListAsync();
        }

        // GET: api/Groups/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Group>> GetGroup(int id)
        {
            var @group = await _context.Groups.FindAsync(id);

            if (@group == null)
            {
                return NotFound();
            }

            return @group;
        }

        // PUT: api/Groups/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutGroup(int id, Group @group)
        {
            if (id != @group.GroupId)
            {
                return BadRequest();
            }

            _context.Entry(@group).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GroupExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Groups
        [HttpPost]
        public async Task<ActionResult<Group>> PostGroup(Group @group)
        {
            _context.Groups.Add(@group);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetGroup", new { id = @group.GroupId }, @group);
        }

        // DELETE: api/Groups/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteGroup(int id)
        {
            var @group = await _context.Groups.FindAsync(id);
            if (@group == null)
            {
                return NotFound();
            }

            _context.Groups.Remove(@group);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool GroupExists(int id)
        {
            return _context.Groups.Any(e => e.GroupId == id);
        }
    }
}

ReactJS Home.js
import React, {useState, useEffect } from 'react';

export function Home(){
  let [groupsData, setGroupsData] = useState([]);

  const populateGroupData = async () => {
    const response = await fetch('api/groups');
    const data = await response.json();
    return data;
}

useEffect(() => {
  populateGroupData()
      .then(data => setGroupsData(data));
}, []);

  return (
      <div>
        <h1>Groups</h1>
        <table className='table table-striped'>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Details</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    {groupsData.map(group =>
                        <tr key={group.groupId}>
                            <td>{group.groupName}</td>
                            <td>{group.description}</td>
                        </tr>
                    )}
                    
                </tbody>
            </table>
      </div>
    );
  }



ReactJS Part 7 .Net Core React Project

 Create-React-App is an excellent option for creating a new React application. Other options also exist. .Net React project can be considered if .Net Core Web API is the REST option for React. It handles a lot of plumbing issues for the developer. The routing is also configured.

 

In this blog I am going to handle the .Net CLI way of creating an .Net Core React application. My favorite editor is Visual Studio Code which comes with a good collection of useful extension. Any editor can be used.  The same is possible with Visual Studio also which I will handle on another blog. 


dotnet new react -o corereact


Inside the ClientApp folder is the ReactJS project.

 


 The .Net Core React Project comes packed with a few components. Notably the NavMenu.js comes with reacter-router.

 


 



ReactJS Part 6 Rendering a List

 ES 6 Map can be use to iterate through a collection of data.

import React, {useState} from "react";
import "./style.css";

export default function App() {
  const [contacts,setContact] = useState([
    {name: 'Shalvin', key:1},
    {name: 'Joy', key:2},
    {name: 'Arun', key:3}
  ]);
  return (
    <div>
     {contacts.map( (contact) =>
        <div>{contact.key} - {contact.name} </div>

     )}
    </div>
  );
}

ReactJS Part 5 State

State are used for changing values within a React Component. 

useState is required to implement State in React functional component. It returns a variable and a function. I am using ES6 array destructing to hold the variable and function. 

 


import React, { useState } from 'react';

function useStateHookDemo(props) {
  let [numberOfClicks, setNumberOfClicks] = useState(123);

  return (
    <div>
      <h1>Number of clicks is {numberOfClicks}</h1>
      <button onClick={() => setNumberOfClicks(numberOfClicks + 1)}>
        Counter
      </button>
    </div>
  );
}

export default useStateHookDemo;

In the button click the function to alter the state variable is called.

Saturday, April 9, 2022

ReactJS Part 4 : Events

All the HTML Controls events are available to React components as props. The event names should have on prefix followed by event name which should be initially capital.

function EventHandling() {
    
    function helloFunction(){
        alert('Hello function')
    }

    const helloArrowSyntax = () => {alert('Hello')}
    return (
    <div>
        <div><button onClick={() => {alert('Hello inline')}}>Hello inline</button></div>
        <div><button onClick={helloFunction}>Hello function</button></div>
        <div><button onClick={helloArrowSyntax}>Hello Arrow Syntax</button></div>
    </div>
  )
}
export default EventHandling



ReactJS Part3 : Props

Props allows pass data to a component. 

In this example we can pass data from the parent component ie. App.js to the child component ie. Contact.js.

Contact.js

import React from 'react'

function Contact(props) {
  return (
    <div>{props.name}</div>
  )
}
export default Contact

App.js

import Contact from './components/Contact';

function App() {
  return (
    <div>
       <h3>Props</h3>
       
       <Contact name = "Shalvin P D"/>
       <Contact name = "Arun Kumar"/>
    </div>
  );
}
export default App;



Here is the Contact.js functional component making use of ES6 arrow syntax.

const Contact = (props) =>  {
  return (
    <div>{props.name}</div>
  )
}
export default Contact

Thursday, April 7, 2022

ReactJS Part 2 Create React App



Create-react-app

Create React App is the preferred way to create a React Application. NodeJS should be installed prior to executing npm create-react-app. The reason why we install NodeJS is to have npm (Node Package  Manager). Other than that nothing related to NodeJS is required in ReactJS.

 >npx  create-react-app hello-react1

 

 

 

>npm start


 

 

package.json file contains all the dependencies of ReactJS appllication.

src folder contains the source code of your application.

Inside the public folder there is index.html file which is the only html page of the React Single Page application.


App.js
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
     <h2>Shalvin P D</h2>
    </div>
  );
}

export default App;

  The basic building block of  React is Component. A component can be written either using class or a function. Here I am creating a functional component called App. JSX is used to create react components. JSX will in turn be converted to JavaScript.

Index.js

import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root')
);

Index.js is the first file to execute. Index.js is making using of App component created earlier.

Here App is the root component. Every React app will have one and only root component.


Visual Studio Code

You can use any editor for creating React applications. My preferred choice is Visual Studio Code. Visual Studio Code is a free and feature rich editor with plenty of Extensions.

I will be using ES7+ React/Redux/React-Native snippets for creating ReactJS applications.

 

 Creating Component
Inside the src folder I have created at folder called components. Inside the component folder I have created a file called Contact.js. 
 
rfce
 
In  the Contact.js file I typed rfce tab which created the code for a functional component with default export. 
 
Contact.js
function Contacts() {
  return (
    <div>Contacts</div>
  )
}
export default Contacts


function App() {
  return (
    <div className="App">
        <h2>Shalvin P D</h2>
        <Contacts/>
    </div>
  );
}
export default App;


Data

function Contacts() {
    let location = 'Kochi'
  return (
    <div>Located at {location}</div>
  )
}
export default Contacts 


import Contacts from './components/Contacts';

function App() {
  return (
    <div className="App">
        <h2>Shalvin P D</h2>
        <Contacts/>
    </div>
  );
}
export default App;