article

Monday, September 13, 2021

SwiftUI Detect Device rotation portrait and landscape orientation

SwiftUI Detect Device rotation portrait and landscape orientation

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct DeviceRotationViewModifier: ViewModifier {
    let action: (UIDeviceOrientation) -> Void

    func body(content: Content) -> some View {
        content
            .onAppear()
            .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
                action(UIDevice.current.orientation)
            }
    }
}

extension View {
    func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
        self.modifier(DeviceRotationViewModifier(action: action))
    }
}

struct ContentView: View {
    @State private var orientation = UIDeviceOrientation.unknown

    var body: some View {
        Group {
            if orientation.isPortrait {
                Text("Portrait")
            } else if orientation.isLandscape {
                Text("Landscape")
            } else if orientation.isFlat {
                Text("Flat")
            } else {
                Text("Unknown")
            }
        }
        .onRotate { newOrientation in
            orientation = newOrientation
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Friday, September 10, 2021

SwiftUI Video Player - How to play video AVPlayer

SwiftUI Video Player - How to play video AVPlayer

test video : https://test-videos.co.uk/bigbuckbunny/mp4-h264

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI
import AVKit

struct ContentView: View {
    
    var body: some View {
        GeometryReader { geo in
            ZStack {
                
                player().frame(height: UIDevice.current.orientation.isLandscape ? geo.size.height : geo.size.height / 3)
                    .edgesIgnoringSafeArea(.all)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct player : UIViewControllerRepresentable {
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<player>) -> AVPlayerViewController {
        
        let player1 = AVPlayer(url: URL(string: "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4")!)
        
        let controller = AVPlayerViewController()
        controller.player = player1
        return controller
    }
    
    func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<player>)  {
        
        
    }
}

PHP Convert Data from MySQL to JSON - result.json file

PHP Convert Data from MySQL to JSON - result.json file

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `posts` (`id`, `title`, `content`, `link`, `timestamp`) VALUES
(4, 'What is AngularJS', 'AngularJS is a JavaScript MVC framework  developed by Google that lets you build well structured, easily testable,  declarative and maintainable front-end applications which provides solutions to  standard infrastructure concerns.', 'link-5', '2021-03-20 16:00:00'),
(5, 'What is MongoDB', 'It is a quick tutorial on MongoDB and how you can install it on your Windows OS. We will also learn some basic commands in MongoDB for example, creating and dropping a Database, Creation of a collection and some more operations related to the collection.', 'link-6', '2021-03-21 16:00:00'),
(6, 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'link-6', '2021-03-20 16:00:00'),
(7, 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'link-7', '2021-03-14 16:00:00'),
(8, 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'link-8', '2021-03-20 16:00:00'),
(9, 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'link-9', '2021-03-19 16:00:00'),
(10, 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'link-10', '2021-03-15 16:00:00'),
(11, 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'link-11', '2021-03-14 16:00:00');

ALTER TABLE `posts`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `posts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;

index.php
//index.php
<!doctype html>
<html>
<head>
<title>PHP Convert Data from MySQL to JSON - result.json file </title>
</head>
<body >
<?php 
include 'config.php';

$response = array();
$posts = array();

$query = "SELECT * FROM posts limit 20";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
    $title = $row['title'];
    $url = $row['link'];
	$posts[] = array('title'=> $title, 'url'=> $url);
}

$response['posts'] = $posts;

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
 ?>
</body>
</html>
config.php
//config.php
<?php
$host = "localhost"; 
$user = "root";
$password = ""; 
$dbname = "testingdb"; 

$con = mysqli_connect($host, $user, $password,$dbname);
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

Thursday, September 9, 2021

SwiftUI how to create Custom Bar Chart

SwiftUI how to create Custom Bar Chart

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var bar1 : CGFloat = 0
    
    var body: some View {
        
        GeometryReader {geo in
            VStack {
            
                HStack {
                    
                    Button(action:  {
                        self.bar1 = geo.size.width / 2 - 20
                    }) {
                        Text("Day 1").padding(15)
                    }
                    .background(Color.orange)
                    .foregroundColor(.white)
                    .cornerRadius(8)
                    
                    Button(action:  {
                        self.bar1 = geo.size.width * 0.25 - 20
                    }) {
                        Text("Day 2").padding(15)
                    }
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(8)
                    
                    Button(action:  {
                        self.bar1 = geo.size.width * 0.25 - 90
                    }) {
                        Text("Day 3").padding(15)
                    }
                    .background(Color.red)
                    .foregroundColor(.white)
                    .cornerRadius(8)
                }
                
                Bar(percent: self.bar1, color: .green)
                
            }// End VStack
            .onAppear {
                self.bar1 = geo.size.width / 2 - 20
            }.animation(.spring())
        }
    }
}

struct Bar : View {
    
    var percent : CGFloat = 0
    var color : Color = .white
    
    var body: some View {
        
        HStack {
            Capsule().fill(color).frame(width: percent, height: 30)
            
            Spacer()
        }.padding(10)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Wednesday, September 8, 2021

SwiftUI How to Store Data using User Defaults

SwiftUI How to Store Data using User Defaults

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var msg = ""
    @State var retrived = ""
    
    var body: some View {
        
        VStack {
            
            Text(retrived).fontWeight(.heavy)
            
            TextField("Enter msg to Save", text: $msg)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
            
            Button (action: {
                UserDefaults.standard.set(self.msg, forKey: "Msg")
                self.retrived = self.msg
                self.msg = ""
            }) {
                Text("Save").padding()
            }.background(Color.orange)
            .foregroundColor(.white)
            .cornerRadius(9)
        }
        .onAppear {

            guard let retreivedmsg = UserDefaults.standard.value(forKey: "Msg") else { return }
            
            self.retrived = retreivedmsg as! String
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

ReactJS Multistep Forms With Semantic UI

ReactJS Multistep Forms With Semantic UI

In this tutorial, you will build a multistep registration form with React and Semantic UI.

https://react.semantic-ui.com/
src/index.js
 
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'semantic-ui-css/semantic.min.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { Component } from 'react';
import { Grid } from 'semantic-ui-react';
import Main from './components/Main';

class App extends Component {
  render() {
    return (
		<div>
		  <p><h1>ReactJS Multistep Forms With Semantic UI</h1></p>
		  <Grid>
			<Grid.Row columns={3}>
			  <Grid.Column></Grid.Column>
			  <Grid.Column>
				<Main />
			  </Grid.Column>
			  <Grid.Column></Grid.Column>
			</Grid.Row>
		  </Grid>
	  </div>
    );
  }
}
  
export default App;
src/Components/Main.js
/src/Components/Main.js
import React, { Component } from 'react';
import UserDetails from './UserDetails';
import PersonalDetails from './PersonalDetails';
import Confirmation from './Confirmation';
import Success from './Success';

class Main extends React.Component { 
  
  state = {
    step: 1,
    firstName: '',
    lastName: '',
    email: '',
    age: '',
    city: '',
    country: ''
  }
  
  nextStep = () => {
    const { step } = this.state
    this.setState({
      step : step + 1
    })
  }

  prevStep = () => {
    const { step } = this.state
    this.setState({
      step : step - 1
    })
  }

  handleChange = input => event => {
    this.setState({[input]: event.target.value})
  }
  
  render() {
    const { step } = this.state;
    const { firstName, lastName, email, age, city, country } = this.state;
    const values = { firstName, lastName, email, age, city, country };

    switch(step) {
      case 1:
        return <UserDetails
                  nextStep={this.nextStep} 
                  handleChange = {this.handleChange}
                  values={values}
                />
      case 2:
        return <PersonalDetails
                  nextStep={this.nextStep}
                  prevStep={this.prevStep}
                  handleChange = {this.handleChange}
                  values={values}
                />
      case 3:
        return <Confirmation
                  nextStep={this.nextStep}
                  prevStep={this.prevStep}
                  values={values}
                />
      case 4:
        return <Success />
    }
  }
}

export default Main;
src/components/UserDetails.js
//src/components/UserDetails.js
import React, { Component } from 'react';
import { Grid, Header, Segment, Form, Button } from 'semantic-ui-react';

class UserDetails extends Component {
  saveAndContinue = (e) => {
    e.preventDefault();
    this.props.nextStep();
  }

  render() {
    const { values } = this.props;

    return (
      <Grid.Column style={{ maxWidth: 450 }}>
        <Header textAlign='center'>
          <h1>Enter User Details</h1>
        </Header>

        <Form>
          <Segment>
            <Form.Field>
              <label>First Name</label>
              <input
                placeholder='First Name'
                onChange={this.props.handleChange('firstName')}
                defaultValue={values.firstName}
              />
            </Form.Field>

            <Form.Field>
              <label>Last Name</label>
              <input
                placeholder='Last Name'
                onChange={this.props.handleChange('lastName')}
                defaultValue={values.lastName}
              />
            </Form.Field>

            <Form.Field>
              <label>Email Address</label>
              <input
                type='email'
                placeholder='Email Address'
                onChange={this.props.handleChange('email')}
                defaultValue={values.email}
              />
            </Form.Field>
          </Segment>

          <Segment>
            <Button onClick={this.saveAndContinue}>Save And Continue</Button>
          </Segment>
        </Form>
      </Grid.Column>
    );
  }
}

export default UserDetails;
src/components/PersonalDetails.js
//src/components/PersonalDetails.js
import React, { Component } from 'react';
import { Grid, Header, Segment, Form, Button } from 'semantic-ui-react';

class PersonalDetails extends Component {
  saveAndContinue = (e) => {
    e.preventDefault();
    this.props.nextStep();
  }

  back = (e) => {
    e.preventDefault();
    this.props.prevStep();
  }

  render() {
    const { values } = this.props;

    return (
      <Grid.Column style={{ maxWidth: 450 }}>
        <Header textAlign='center'>
          <h1>Enter Personal Details</h1>
        </Header>

        <Form>
          <Segment>
            <Form.Field>
              <label>Age</label>
              <input placeholder='Age'
                onChange={this.props.handleChange('age')}
                defaultValue={values.age}
              />
            </Form.Field>

            <Form.Field>
              <label>City</label>
              <input placeholder='City'
                onChange={this.props.handleChange('city')}
                defaultValue={values.city}
              />
            </Form.Field>

            <Form.Field>
              <label>Country</label>
              <input placeholder='Country'
                onChange={this.props.handleChange('country')}
                defaultValue={values.country}
              />
            </Form.Field>
          </Segment>

          <Segment textAlign='center'>
            <Button onClick={this.back}>Back</Button>

            <Button onClick={this.saveAndContinue}>Save And Continue</Button>
          </Segment>
        </Form>
      </Grid.Column>
    )
  }
}

export default PersonalDetails;
src/components/Confirmation.js
//src/components/Confirmation.js
import React, { Component } from 'react';
import { Grid, Header, Segment, Button, List } from 'semantic-ui-react';

class Confirmation extends Component {
  saveAndContinue = (e) => {
    e.preventDefault();
    this.props.nextStep();
  }

  back = (e) => {
    e.preventDefault();
    this.props.prevStep();
  }

  render() {
    const { values: { firstName, lastName, email, age, city, country } } = this.props;

    return (
      <Grid.Column style={{ maxWidth: 450 }}>
        <Header textAlign='center'>
          <h1>Confirm your Details</h1>

          <p>Click Confirm if the following details have been correctly entered</p>
        </Header>

        <Segment>
          <List divided relaxed>
            <List.Item>
              <List.Icon name='users' size='large' />
              <List.Content>First Name: {firstName}</List.Content>
            </List.Item>

            <List.Item>
              <List.Icon name='users' size='large' />
              <List.Content>Last Name: {lastName}</List.Content>
            </List.Item>

            <List.Item>
              <List.Icon name='mail' size='large' />
              <List.Content>Email: {email}</List.Content>
            </List.Item>

            <List.Item>
              <List.Icon name='calendar' size='large' />
              <List.Content>Age: {age}</List.Content>
            </List.Item>

            <List.Item>
              <List.Icon name='marker' size='large' />
              <List.Content>Location: {city}, {country}</List.Content>
            </List.Item>
          </List>
        </Segment>

        <Segment textAlign='center'>
          <Button onClick={this.back}>Back</Button>

          <Button onClick={this.saveAndContinue}>Confirm</Button>
        </Segment>
      </Grid.Column>
    )
  }
}

export default Confirmation;
src/Success.js
//src/Success.js
import React, { Component } from 'react';
import { Grid, Header } from 'semantic-ui-react';

class Success extends Component {
  render() {
    return (
      <Grid.Column style={{ maxWidth: 450 }}>
        <Header textAlign='center'>
          <h1>Details Successfully Saved</h1>
        </Header>
      </Grid.Column>
    )
  }
}

export default Success;

Monday, September 6, 2021

SwiftUI Horizontal List - Horizontal Scroll View

SwiftUI Horizontal List - Horizontal Scroll View

In this tutorial i'm going to show how to implement horizontal list in SwiftUI.

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        
        ScrollView(.horizontal, showsIndicators : false) {
            HStack {
                ForEach(0..<5) { i in
                    cardView(img: "photo\(i)")
                }
            }
        }
    }
}

struct cardView : View {
    var img = ""
    
    var body: some View {
        VStack {
            Image(img)
                .resizable()
                
        }
        .frame(width: 250, height: 400)
        .cornerRadius(20)
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SwiftUI JSON Parsing with SDWebImageSwiftUI and Details View

SwiftUI JSON Parsing with SDWebImageSwiftUI and Details View

JSON Data
https://api.github.com/users/hadley/orgs

SDWebImageSwiftUI
https://github.com/SDWebimage/SDWebimageSwiftUI


ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI
import SDWebImageSwiftUI

struct ContentView: View {
    
    @ObservedObject var getData = datas()
    
    var body: some View {
        NavigationView {
            List(getData.jsonData) { i in
                NavigationLink(destination : Details(userItem: i)) {
                    ListRow(url: i.avatar_url, name: i.login)
                }
            }.navigationBarTitle("Json Parsing")
        }
    }
}

class datas: ObservableObject {
  @Published var jsonData = [datatype]()
      
    init() {
        let url = URL(string: "https://api.github.com/users/hadley/orgs")!
        URLSession.shared.dataTask(with: url) {(data, response, error) in
            do {
                if let jsData = data {
                    let decodedData = try JSONDecoder().decode([datatype].self, from: jsData)
                    DispatchQueue.main.async {
                        self.jsonData = decodedData
                    }
                } else {
                    print("No data")
                }
            } catch {
                print("Error")
            }
        }.resume()
    }
}

struct datatype : Identifiable, Decodable {
    var id : Int
    var login : String
    var node_id : String
    var avatar_url : String
}

struct ListRow : View {
    
    var url : String
    var name : String
    
    var body: some View {
        HStack {
            AnimatedImage(url: URL(string: url)).resizable().frame(width: 60, height: 60).clipShape(Circle()).shadow(radius: 20)
            
            Text(name).fontWeight(.heavy).padding(.leading, 10)
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Details.swift
 
//
//  Details.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI
import SDWebImageSwiftUI

struct Details: View {
    
    let userItem : datatype
    
    var body: some View {
        VStack {
            Text("Username : \(userItem.login)")
                .font(.title2)
            
            let url = userItem.avatar_url
            
            AnimatedImage(url: URL(string: url)).resizable().frame(width: 160, height: 160).clipShape(Circle()).shadow(radius: 20)
        }
    }
}

Sunday, September 5, 2021

SwiftUI Simple Instagram Design

SwiftUI Simple Instagram Design

In this tutorial I'm going to show how design instagram with SwiftUI.

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        TabView {
            NavigationView {
                Homepage().navigationTitle("Instagram")
                .navigationBarItems(leading:
                    Button(action: {
                                            
                    }, label: {
                        Image(systemName: "camera.fill").resizable().frame(width: 35, height: 35)
                    }), trailing:
                        
                    HStack {
                        Button(action: {
                            
                        }, label: {
                            Image(systemName: "tv").resizable().frame(width: 35, height: 35)
                        })
                        Button(action: {
                            
                        }, label: {
                            Image(systemName: "paperplane.circle.fill").resizable().frame(width: 35, height: 35)
                        })
                    }
                )
            }.tabItem {
                Image(systemName: "house.fill")
            }
            
            Text("Find").tabItem {
                Image(systemName: "magnifyingglass.circle")
            }
            Text("Add").tabItem {
                Image(systemName: "person.badge.plus")
            }
            Text("Likes").tabItem {
                Image(systemName: "suit.heart.fill")
            }
            Text("Bio").tabItem {
                Image(systemName: "person.fill.questionmark")
            }
        }
    }
}

struct Homepage : View {
    var body: some View {
        ScrollView(.vertical, showsIndicators: true) {
            VStack {
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack{
                        ForEach(0..<6) { i in
                            VStack {
                                Image("photo\(i)")
                                    .resizable()
                                    .clipShape(Circle())
                                .frame(width: 80, height: 80)
                                .overlay(Circle().stroke(lineWidth: 3).fill(Color.red))
                                .padding(6)
                                Text("User \(i)")
                            }
                        }
                    }
                }
                
                ForEach(0..<5) { photo in
                    Feeds()
                }
            }
        }
    }
}

struct Feeds : View {
    
    var body: some View {
        
        VStack(alignment: .leading, content: {
            HStack {
                Image("photo1")
                    .resizable()
                    .frame(width: 30, height: 30).clipShape(Circle())
                Text("User")
                    .fontWeight(.light)
                Spacer()
                
                Button(action: {

                }) {
                    Image(systemName: "line.horizontal.3").resizable().frame(width: 15, height: 15)
                }
            }
            
            Image("3")
                .resizable()
                .padding([.top, .bottom], 8)
            
            HStack {
                Button(action: {

                }) {
                    Image(systemName: "message").resizable().frame(width: 30, height: 30)
                }
                
                Button(action: {

                }) {
                    Image(systemName: "paperplane.fill").resizable().frame(width: 30, height: 30)
                }
                
                Spacer()
                
                Button(action: {

                }) {
                    Image(systemName: "bookmark.fill").resizable().frame(width: 30, height: 30)
                }
            }.padding(8)
            
            Text("983 Likes")
            Text("View All 680 Comments")
        })
        .padding()
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

ReactJS Datepicker

ReactJS Datepicker

In this tutorial, we will have a look at one of the most popular datepicker packages for React.

Install the react-datepicker Node.js package.

https://www.npmjs.com/package/react-datepicker

npm install react-datepicker --save

C:\reactdev\myreactdev>npm install react-datepicker --save

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date()
    };
    this.dateChange = this.dateChange.bind(this);
  }
  dateChange(date) {
    this.setState({
      date: date
    },
     () => {
      console.log(this.state.date);
    });
  }

  render() {
    return (
      <div>
        <p>
          Pick a date:
        </p>
        <DatePicker selected={this.state.date} onChange={this.dateChange} dateFormat="MMMM d, yyyy"/>
      </div>
    );
  }
}
export default App;

Saturday, September 4, 2021

ReactJS Simple Select Option Dropdown

ReactJS Simple Select Option Dropdown

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
    super(props);
    this.selectCountry = this.selectCountry.bind(this);
    this.state = {
      countries: [],
      gender: {}
    };
  }
  componentDidMount() {
    this.setState({
      countries: [
        {id: 'AFG', name: 'Afghanistan'},
        {id: 'DZ', name: 'Algeria'},
        {id: 'ALB', name: 'Albania'},
        {id: 'PH', name: 'Philippines'},
        {id: 'US', name: 'United States'}
      ]
    });

    this.setState({
      gender: {
        "Male": "Male",
        "Female": "Female"
      }
    });
  }

  selectCountry = (e) => {
    let idx = e.target.value;
    alert(idx)
  }
  render() {
    const { countries } = this.state;
    const { gender } = this.state;

    let countriesList = countries.length > 0
    	&& countries.map((item, i) => {
      return (
        <option key={i} value={item.id}>{item.name}</option>
      )
    }, this);

    let genderList = Object.keys(gender).map((k) => {
      return (
        <option key={k} value={k}>{gender[k]}</option>
      )
    }, this);

    return (
      <div className="container">
        <div className="row">
          <h1>ReactJS Simple Select Option Dropdown</h1>
          <form>
          <div className="form-group">
            <label>Country: </label>
            <select className="form-select" onChange={this.selectCountry}>
              {countriesList}
            </select>
          </div>
          <div className="form-group">
          <label>Gender: </label>
            <select className="form-select">
              {genderList}
            </select>
          </div>
          </form>
        </div>
      </div>
    );
  }
}export default App;

Thursday, September 2, 2021

ReactJS Form bootstrap with Validation

ReactJS Form bootstrap with Validation

install bootstrap
C:\reactdev\myreactdev>npm install bootstrap

add to src/index.js
import 'bootstrap/dist/css/bootstrap.css';

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS Form with Validation</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { Component } from 'react';
import './App.css';
import Form from './Form.js';
class App extends Component {
  render() {
    return (
      <div className="App">        
        <Form />
      </div>
    );
  }
}export default App;
src/Form.js
//src/Form.js
import React, { Component } from 'react';
import { FormValidation } from './FormValidation';

class Form extends Component {
	
constructor (props) {
    super(props);
    this.state = {
      email: '',
      password: '',
      FormValidation: {email: '', password: ''},
      validateEmail: false,
      validatePassword: false,
      validateForm: false
    }
  }

  validateUserInput = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value},
                  () => { this.validateInputField(name, value) });
  }

  validateInputField(inputField, value) {
    let inputFieldErrors = this.state.FormValidation;
    let validateEmail = this.state.validateEmail;
    let validatePassword = this.state.validatePassword;

    switch(inputField) {
      case 'email':
        validateEmail = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
        inputFieldErrors.email = validateEmail ? '' : ' is invalid!';
        break;
      case 'password':
        validatePassword = value.length >= 6;
        inputFieldErrors.password = validatePassword ? '': ' is too short!';
        break;
      default:
        break;
    }
    this.setState({FormValidation: inputFieldErrors,
                    validateEmail: validateEmail,
                    validatePassword: validatePassword
                  }, this.validateForms);
  }

  validateForms() {
    this.setState({validateForm: this.state.validateEmail && this.state.validatePassword});
  }

  cmdSubmit(event) {  
      alert('You have entered the email and passwor successfully.');  
      event.preventDefault();  
  }
render () {
    return (	
	  <div className="container">
      <div className="col-md-6 mx-auto text-center">
         <div className="header-title">
            <h1 className="wv-heading--title">
              ReactJS Form with Validation
            </h1>
            <h2 className="wv-heading--subtitle">
               React bootstrap
            </h2>
         </div>
      </div>
      <div className="row">
         <div className="col-md-6 mx-auto">
            <div className="myform form ">
			  <form className="signupForm" onSubmit={this.cmdSubmit}>
				<h5>Sign up Form</h5>
				<div className="panel panel-default">
				  <FormValidation FormValidation={this.state.FormValidation} />
				</div>
				<div className="form-group">
				  <label htmlFor="email">Email</label>
				  <input type="email" required className="form-control" name="email"
					placeholder="Email"
					value={this.state.email}
					onChange={this.validateUserInput}  />
				</div>
				<div className="form-group">
				  <label htmlFor="password">Password</label>
				  <input type="password" className="form-control" name="password"
					placeholder="Password"
					value={this.state.password}
					onChange={this.validateUserInput}  />
				</div>
        <br/>
				<div className="text-center">
				<button type="submit" className="btn btn-primary send-button" disabled={!this.state.validateForm}>Sign up</button>
				</div>
				  <div className="col-md-12 ">
                     <div className="login-or">
                        <hr className="hr-or"/>
                        <span className="span-or">or</span>
                     </div>
                  </div>
                  <div className="form-group">
                     <button type="submit" className="btn btn-block g-button">
                     <i className="fa fa-google"></i> Sign up with Google
                     </button>
                  </div>
                  <p className="small mt-3">By signing up, you are indicating that you have read and agree to the Terms of Use and Privacy Policy.
                  </p>
			  </form>
            </div>
         </div>
      </div>
	  </div>
    )
  }
}
export default Form;
src/FormValidation.js
//src/FormValidation.js
import React from 'react';

export const FormValidation = ({FormValidation}) =>
<div className='FormValidation'>
{Object.keys(FormValidation).map((fieldName, i) => {
  if(FormValidation[fieldName].length > 0){
	return (
	  <p class="alert alert-danger" key={i}>{fieldName} {FormValidation[fieldName]}</p>
	)        
  } else {
	return '';
  }
})}
</div>
//src/App.css
.send-button{
width:100%;
font-weight: 600;
color:#fff;
padding: 8px 25px;
}
.g-button{
color: #fff !important;
border: 1px solid #EA4335;
background: #ea4335 !important;
width:100%;
font-weight: 600;
color:#fff;
padding: 8px 25px;
}
.my-input{
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
cursor: text;
padding: 8px 10px;
transition: border .1s linear;
}
.header-title{
margin: 5rem 0;
}
h1{
font-size: 31px;
line-height: 40px;
font-weight: 600;
color:#4c5357;
}
h2{
color: #5e8396;
font-size: 21px;
line-height: 32px;
font-weight: 400;
}
.login-or {
position: relative;
color: #aaa;
margin-top: 10px;
margin-bottom: 10px;
padding-top: 10px;
padding-bottom: 10px;
}
.span-or {
display: block;
position: absolute;
left: 50%;
top: -2px;
margin-left: -25px;
background-color: #fff;
width: 50px;
text-align: center;
}
.hr-or {
height: 1px;
margin-top: 0px !important;
margin-bottom: 0px !important;
}
@media screen and (max-width:480px){
h1{
font-size: 26px;
}
h2{
font-size: 20px;
}
}

Wednesday, September 1, 2021

SwiftUI Custom TopBar - Picker In SwiftUI

SwiftUI Custom TopBar - Picker In SwiftUI

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var currentTab = 0
    
    var body: some View {
        VStack{
            Picker(selection: $currentTab, label: Text("")) {
                Image(systemName: "house.fill").tag(0)
                Image(systemName: "person.crop.circle").tag(1)
                Image(systemName: "paperplane.fill").tag(2)
            }.pickerStyle(SegmentedPickerStyle())
            .padding(.top, 10)
            
            Spacer()
            
            if currentTab == 0 {
                page1()
            }
            if currentTab == 1 {
                page2()
            }
            if currentTab == 2 {
                page3()
            }
        }
    }
}

struct page1: View {
    var body: some View {
        VStack {
            Text("page 1")
            Image("photo1")
                
        }
    }
}

struct page2: View {
    var body: some View {
        VStack {
            Text("page 2")
            Image("photo2")
                
        }
    }
}

struct page3: View {
    var body: some View {
        VStack {
            Text("page 3")
            Image("photo3")
                
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Monday, August 30, 2021

ReactJS - Autocomplete Json data

ReactJS - Autocomplete Json data

Autocomplete allows users to have other suggested strings or values displayed on typing of the relevant text in the input field.
src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
 
ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS - Autocomplete</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
import json from './data/results.json';

class App extends React.Component {
	constructor(props) {
		super(props);
		this.state = { suggestions:[] };
		this.search = this.search.bind(this);
	}
	
	search(event) {
		let input = event.target.value;
		//console.log('event.target.value: ' + input);
		console.log('this.searchResults: ' + json);
		let matches = [], i;
		
		if (input.length > 1) {
			for (i = 0; i < json.length; i++) {
				if (json[i].match(input)) {
					matches.push(json[i]);
				}
			}
		}
		
		this.setState({ suggestions: matches });
	}

	render() {
		return (
			<div>
        <h2>ReactJS - Autocomplete</h2>
				<label>Search Here</label>  <input onKeyUp={this.search.bind(this)}/> 
				<React.Fragment>
					<ul style={{listStyleType:'none'}}>
						{this.state.suggestions.map(res => (
							<li key={res}>
								{res}
							</li>
						))}
					</ul>
				</React.Fragment>
			</div>
		);
	}
}

export default App; 
src/data/results.json
[
	"Leanne Graham",
	"Ervin Howell",
	"Clementine Bauch",
	"Patricia Lebsack",
	"Chelsey Dietrich",
	"Mrs. Dennis Schulist",
	"Kurtis Weissnat",
	"Nicholas Runolfsdotti",
	"Glenna Reichert",
	"Clementina DuBuque",
	"Airi Satou",
	"Angelica Ramos",
	"Ashton Cox",
	"Bradley Greer",
	"Brenden Wagner",
	"Brielle Williamson",
	"Bruno Nash",
	"Caesar Vance",
	"Cara Stevens"
] 

Sunday, August 29, 2021

ReactJS API Call Json

ReactJS API Call Json

In this tutorial we will show how to call API in ReactJS. The API calls are made to get data and render into application.

src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" crossorigin="anonymous">
    <title>ReactJS - API Call</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, {Component} from 'react';
import User from './user';

class App extends Component {

    state = {
      user: []
    };
    //componentDidMount() method  is called immediately when component mounted and the API call made in this method using fetch method
    //fetch method make GET request to API and parse the response into json using res.json()
    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/users')
            .then(res => res.json())
            .then((data) => {
                this.setState({ user: data })
            })
            .catch(console.log)
    }

    render() {
      return (
          <User user={this.state.user} />
      )
    }
}

export default App; 
src/user.js
//src/user.js
import React from 'react'

const User = ({user}) => {
    return (
        <div>
            <center><h1>API Call Json- User List</h1></center>
            {user.map((emp) => (
                <div class="card">
                    <div className="card-body">
                        <h5 className="card-title">{emp.name}</h5>
                        <h6 className="card-subtitle mb-2 text-muted">{emp.email}</h6>
                        <p className="card-text">{emp.company.catchPhrase}</p>
                    </div>
                </div>
            ))}
        </div>
    )
};

export default User

ReactJS - Router

ReactJS - Router

React Router is used to define multiple routes in the application.

Routing is a process in which a user is directed to different pages based on their action or request.

React Router Installation

react-router-dom: It is used for web applications design.

https://www.npmjs.com/package/react-router-dom

$ npm install --save react-router-dom

C:\reactdev\myreactdev>npm install --save react-router-dom
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Route, Link, BrowserRouter as Router, NavLink, Switch} from 'react-router-dom' 
import App from './App';
import About from './About'  
import Contact from './Contact'  
import Notfound from './notfound'  

const routing = (  
  <Router>  
    <div>  
      <h1>React Router Example</h1>  
      <ul>  
        <li>  
          <NavLink to="/" exact activeStyle={  
             {color:'red'}  
          }>Home</NavLink>  
        </li>  
        <li>  
          <NavLink to="/about" exact activeStyle={  
             {color:'green'}  
          }>About</NavLink>  
        </li>  
        <li>  
          <NavLink to="/contact" exact activeStyle={  
             {color:'magenta'}  
          }>Contact</NavLink>  
        </li>  
      </ul>
      <Switch>  
         <Route exact path="/" component={App} />  
         <Route path="/about" component={About} />  
         <Route path="/contact" component={Contact} />  
         <Route component={Notfound} />  
      </Switch> 
    </div>  
  </Router>  
)  
ReactDOM.render(routing, document.getElementById('root'));  
public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react'  
class App extends React.Component {  
  render() {  
    return (  
      <div>  
        <h1>Home</h1>  
      </div>  
    )  
  }  
}  
export default App  
src/About.js
//src/About.js
import React from 'react'  
class About extends React.Component {  
  render() {  
    return <h1>About</h1>  
  }  
}  
export default About  
src/Contact.js
//src/Contact.js
import React from 'react'  
import { Route, Link } from 'react-router-dom'  
  
const Contacts = ({ match }) => <p>{match.params.id}</p>  
  
class Contact extends React.Component {  
  render() {  
    const { url } = this.props.match  
    return (  
      <div>  
        <h1>Welcome to Contact Page</h1>  
        <strong>Select contact Id</strong>  
        <ul>  
          <li>  
            <Link to="/contact/1">Contacts 1 </Link>  
          </li>  
          <li>  
            <Link to="/contact/2">Contacts 2 </Link>  
          </li>  
          <li>  
            <Link to="/contact/3">Contacts 3 </Link>  
          </li>  
          <li>  
            <Link to="/contact/4">Contacts 4 </Link>  
          </li>  
        </ul>  
        <Route path="/contact/:id" component={Contacts} />  
      </div>  
    )  
  }  
}  
export default Contact  
notfound.js
//notfound.js
import React from 'react'  
const Notfound = () => <h1>Not found</h1>  
export default Notfound  

Saturday, August 28, 2021

ReactJS Form and CSS

ReactJS Form and CSS

src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
//React Forms
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { username: '' };
  }
  myChangeHandler = (event) => {
    this.setState({username: event.target.value});
  }
  render() {
    return (
      <form>
      <h1>Hello {this.state.username}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        onChange={this.myChangeHandler}
      />
      </form>
    );
  }
}
export default App;
src/App.js
//import React from 'react';
import React, { useReducer, useState } from 'react';
import './App.css';

const formReducer = (state, event) => {
  if(event.reset) {
   return {
     apple: '',
     count: 0,
     name: '',
     'gift-wrap': false,
   }
 }
  return {
    ...state,
    [event.name]: event.value
  }
}

function App() {
  const [formData, setFormData] = useReducer(formReducer, {
    count: 100,
  });
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = event => {
    event.preventDefault();
    setSubmitting(true);

    setTimeout(() => {
      setSubmitting(false);
      setFormData({
       reset: true
     })
    }, 3000);
  }

  const handleChange = event => {
    const isCheckbox = event.target.type === 'checkbox';
    setFormData({
      name: event.target.name,
      value: isCheckbox ? event.target.checked : event.target.value,
    })
  }

  const mystyle = {
    color: "#495057",
    backgroundColor: "#fff",
    border: "1px solid #ced4da",
    padding: ".375rem .75rem"
  };     
  return(
    <div className="wrapper">
      <h1 style={{color: "red"}}>ReactJS Form and CSS</h1>
      {submitting &&
        <div>
          You are submitting the following:
          <ul>
            {Object.entries(formData).map(([name, value]) => (
              <li key={name}><strong>{name}</strong>: {value.toString()}</li>
            ))}
          </ul>
        </div>
      }
      <form onSubmit={handleSubmit}>
        <fieldset disabled={submitting}>
          <label>
            <p>Name</p>
            <input style={mystyle} name="name" onChange={handleChange} value={formData.name || ''}/>
          </label>
        </fieldset>
        <fieldset disabled={submitting}>
          <label>
            <p>Apples</p>
            <select name="apple" onChange={handleChange} value={formData.apple || ''}>
                <option value="">--Please choose an option--</option>
                <option value="fuji">Fuji</option>
                <option value="Jonagold">Jonagold</option>
                <option value="Cameo">Cameo</option>
                <option value="Empire">Empire</option>
                <option value="McIntosh">McIntosh</option>
                <option value="Golden Delicious">Golden Delicious</option>
            </select>
          </label>
          <label>
            <p>Count</p>
            <input type="number" name="count" onChange={handleChange} step="1" value={formData.count || ''}/>
          </label>
          <label>
            <p>Gift Wrap</p>
            <input type="checkbox" name="gift-wrap" onChange={handleChange} checked={formData['gift-wrap'] || false} disabled={formData.apple !== 'fuji'}/>
          </label>
        </fieldset>
        <button className="button" type="submit" disabled={submitting}>Submit</button>
      </form>
    </div>
  )
}
export default App;
src/App.css
//src/App.css
body {
    background:#fff;
    font-family: Arial;
}
.wrapper {
    padding: 5px 20px;
}

.wrapper fieldset {
    margin: 20px 0;
}

.button {
    display: inline-block;
    position: relative;
    margin: 10px;
    padding: 10px;
    text-align: center;
    text-decoration: none;
    font: bold 12px/25px Arial, sans-serif;
 
    width: 300px;
    color: #3e5706;
    background: #a5cd4e;

    text-shadow: 1px 1px 1px rgba(255,255,255, .22);
 
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 30px;
 
    -webkit-box-shadow: 1px 1px 1px rgba(0,0,0, .29), inset 1px 1px 1px rgba(255,255,255, .44);
    -moz-box-shadow: 1px 1px 1px rgba(0,0,0, .29), inset 1px 1px 1px rgba(255,255,255, .44);
    box-shadow: 1px 1px 1px rgba(0,0,0, .29), inset 1px 1px 1px rgba(255,255,255, .44);
 
    -webkit-transition: all 0.15s ease;
    -moz-transition: all 0.15s ease;
    -o-transition: all 0.15s ease;
    -ms-transition: all 0.15s ease;
    transition: all 0.15s ease;
}

Friday, August 27, 2021

SwiftUI Slide Navigation Menu with animation

SwiftUI Slide Navigation Menu with animation

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var size = UIScreen.main.bounds.width / 1.6
    let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }
    
    var body: some View {
        
        ZStack{
            NavigationView{
                
                //List(0..<5){_ in
                //    Text("Hello Cairocoders")
                //}
                List {
                    ForEach(countryList, id: \.self) { country in
                       Text(country)
                    }
                }
                
                .navigationBarTitle("Home")
                .navigationBarItems(leading: Button(action: {
                    self.size = 10
                }, label: {
                    Image(systemName: "slider.horizontal.3").resizable().frame(width: 30, height: 20)
                }).foregroundColor(.black))
            }
            
            HStack{
                menu(size: $size)
                    .cornerRadius(20)
                        .padding(.leading, -size)
                        .offset(x: -size)
                    Spacer()
            }
        }.animation(.spring())
        
    }
}

struct menu : View {
    
    @Binding var size : CGFloat
    
    var body : some View{
        VStack{
            HStack{
                Spacer()
                Button(action: {
                    self.size =  UIScreen.main.bounds.width / 1.6
                }) {
                    Image(systemName: "xmark.circle").resizable().frame(width: 25, height: 25).padding()
                }.background(Color.red)
                    .foregroundColor(.white)
                .clipShape(Circle())
            }
            
            HStack{
                Image(systemName: "house.fill").resizable().frame(width: 25, height: 25).padding()
                Text("Home").fontWeight(.heavy)
                Spacer()
            }
            .padding(.leading, 20)
            
            HStack{
                Image(systemName: "person.crop.circle").resizable().frame(width: 25, height: 25).padding()
                Text("Profile").fontWeight(.heavy)
                Spacer()
            }
            .padding(.leading, 20)
            
            HStack{
                Image(systemName: "paperplane.fill").resizable().frame(width: 25, height: 25).padding()
                Text("send").fontWeight(.heavy)
                Spacer()
            }
            .padding(.leading, 20)
            
            HStack{
                Image(systemName: "person.crop.circle.fill.badge.exclamationmark").resizable().frame(width: 25, height: 25).padding()
                Text("Log Out").fontWeight(.heavy)
                Spacer()
            }
            .padding(.leading, 20)
            
            Spacer()
            
        }// End VStack
        .frame(width: UIScreen.main.bounds.width / 1.6)
            .background(Color.white)
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Thursday, August 26, 2021

SwiftUI Swipe Menu - Drag Gesture

SwiftUI Swipe Menu - Drag Gesture

In this tutorial I'm going to show how to use drag gesture swipe up-down menu with animations

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var size : CGFloat = UIScreen.main.bounds.height - 140
    
    var body: some View {
        
        ZStack{
            Text("Hello Cairocoders")
                .fontWeight(.heavy)
                .foregroundColor(Color.white)
                
            swipe().cornerRadius(20).padding(15).offset(y: size)
            .gesture(DragGesture()
                .onChanged({ (value) in
                    
                    if value.translation.height > 0{
                        self.size = value.translation.height
                    }
                    else{
                        let temp = UIScreen.main.bounds.height - 140
                        self.size = temp + value.translation.height
                    }
                })
                .onEnded({ (value) in
                    if value.translation.height > 0{
                        if value.translation.height > 200{
                            self.size = UIScreen.main.bounds.height - 140
                        }
                        else{
                            self.size = 15
                        }
                    }
                    else{
                        //since in negative lower value will be greater...
                        if value.translation.height < -200{
                            self.size = 15
                        }
                        else{
                            self.size = UIScreen.main.bounds.height - 140
                        }
                    }
                })).animation(.spring())
            // animation for drag
        }
        .background(Color.gray.edgesIgnoringSafeArea(.all))
    }
}

struct swipe : View {
    
    let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }
    
    var body : some View{
        VStack{
            VStack{
                Text("Swipe up to See More").fontWeight(.heavy).padding([.top,.bottom],15)
            }
            // your custom view here....
            HStack {
                NavigationView {
                    List {
                        ForEach(countryList, id: \.self) { country in
                           Text(country)
                        }
                    }
                    .navigationTitle("Country")
                }
            }
        }.background(Color.white)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

ReactJS Forms

ReactJS Forms

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

src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
//React Forms
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { username: '' };
  }
  myChangeHandler = (event) => {
    this.setState({username: event.target.value});
  }
  render() {
    return (
      <form>
      <h1>Hello {this.state.username}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        onChange={this.myChangeHandler}
      />
      </form>
    );
  }
}
export default App;
src/App.js
//src/App.js
import React from 'react';
//React Forms - Conditional Rendering
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { username: '' };
  }
  myChangeHandler = (event) => {
    this.setState({username: event.target.value});
  }
  render() {
    let header = '';
    if (this.state.username) {
      header = <h1>Hello {this.state.username}</h1>;
    } else {
      header = '';
    }
    return (
      <form>
      {header}
      <p>Enter your name:</p>
      <input
        type='text'
        onChange={this.myChangeHandler}
      />
      </form>
    );
  }
}
export default App;
src/App.js
//src/App.js
import React from 'react';
//React Forms - Submitting Forms
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { username: '' };
  }
  mySubmitHandler = (event) => {
    event.preventDefault();
    alert("You are submitting " + this.state.username);
  }
  myChangeHandler = (event) => {
    this.setState({username: event.target.value});
  }
  render() {
    return (
      <form onSubmit={this.mySubmitHandler}>
      <h1>Hello {this.state.username}</h1>
      <p>Enter your name, and submit:</p>
      <input
        type='text'
        onChange={this.myChangeHandler}
      />
      <input
        type='submit'
      />
      </form>
    );
  }
}
export default App;
src/App.js
//src/App.js
import React from 'react';
//React Forms - Multiple Input Fields
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
    };
  }
  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    this.setState({[nam]: val});
  }
  render() {
    return (
      <form>
      <h1>Hello {this.state.username} {this.state.age}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />
      <p>Enter your age:</p>
      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />
      </form>
    );
  }
}
export default App;
src/App.js
//src/App.js
import React from 'react';
//React Forms - Validating Form Input
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
    };
  }
  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    if (nam === "age") {
      if (!Number(val)) {
        alert("Your age must be a number");
      }
    }
    this.setState({[nam]: val});
  }
  render() {
    return (
      <form>
      <h1>Hello {this.state.username} {this.state.age}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />
      <p>Enter your age:</p>
      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />
      </form>
    );
  }
}
export default App;
src/App.js
//src/App.js
import React from 'react';
//React Forms - Validating Form Input form submit
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
    };
  }
  mySubmitHandler = (event) => {
    event.preventDefault();
    let age = this.state.age;
    if (!Number(age)) {
      alert("Your age must be a number");
    }
  }
  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    this.setState({[nam]: val});
  }
  render() {
    return (
      <form onSubmit={this.mySubmitHandler}>
      <h1>Hello {this.state.username} {this.state.age}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />
      <p>Enter your age:</p>
      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />
      <br/>
      <br/>
      <input type='submit' />
      </form>
    );
  }
}
export default App;
src/App.js
//src/App.js
import React from 'react';
//React Forms - Adding Error Message
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
      errormessage: ''
    };
  }
  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    let err = '';
    if (nam === "age") {
      if (val !="" && !Number(val)) {
        err = <strong>Your age must be a number</strong>;
      }
    }
    this.setState({errormessage: err});
    this.setState({[nam]: val});
  }
  render() {
    return (
      <form>
      <h1>Hello {this.state.username} {this.state.age}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />
      <p>Enter your age:</p>
      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />
      {this.state.errormessage}
      </form>
    );
  }
}
export default App;
src/App.js
//src/App.js
import React from 'react';
//React Forms - 
class App extends React.Component {
  constructor(props) {  
    super(props);  
    this.updateSubmit = this.updateSubmit.bind(this);  
    this.input = React.createRef();  
}  
updateSubmit(event) {  
    alert('You have entered the UserName and CompanyName successfully.');  
    event.preventDefault();  
}  
render() {  
  return (  
    <form onSubmit={this.updateSubmit}>  
      <h1>Uncontrolled Form Example</h1>  
      <label>Name:  
          <input type="text" ref={this.input} />  
      </label>  
      <label>  
          CompanyName:  
          <input type="text" ref={this.input} />  
      </label>  
      <input type="submit" value="Submit" />  
    </form>  
  );  
}  
}  
export default App;

Related Post