Thursday, August 29, 2019

Facebook Login

keytool -exportcert -alias androiddebugkey -keystore android/app/debug.keystore | openssl sha1 -binary | openssl base64

or
Facebook Key hash

Step 1 - Download openssl from the link given bellow
step 2 - Select file according to your system.
After finished download extract the downloaded file.

step -3 create a folder in C drive named 'openssl'

copy the all file from the extracted folder and past it in
openssl folder you just created.
example C:/openssl

step 4 - Go to system search box and type 'cmd'

Past this code in command prompt windows.

"keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | C:\openssl\bin\openssl.exe sha1 -binary | C:\openssl\bin\openssl.exe base64"

step 5 - hit Enter.

it will asked for password, now type 'android' as password
and hit Enter again.

THis process will generate a 27 digi key hash copy the hash including =sign

note it key -alias ==>androiddebugkey
.......................................................................................................................................................................................................................................
Example : #1 [React Native Tutorial: Facebook Login Example]
Step: #1.1

Setup a Facebook App





..................................................................................................................................................................................................................................
Step: #1.2



..................................................................................................................................................................................................................................
Step: #1.3


..................................................................................................................................................................................................................................
Step: #1.4
Click the Facebook Login Set up button.






..................................................................................................................................................................................................................................
Step: #1.5

..................................................................................................................................................................................................................................

Step: #1.6




..................................................................................................................................................................................................................................
Step: #1.7
we need to create a Key Hashes. To get the key hashes.

https://code.google.com/archive/p/openssl-for-windows/downloads

- download and Extract it, and also set the path of  bin  looks like [C:\Users\sapan\Downloads\openssl-0.9.8k_X64\bin]
- open a command prompt and copy and paste the below command.

keytool -exportcert -alias androiddebugkey -keystore android/app/debug.keystore | openssl sha1 -binary | openssl base64







..................................................................................................................................................................................................................................

Step: #1.8


..................................................................................................................................................................................................................................

Step: #1.9

android/app/res/values/strings.xml then add this value.






..................................................................................................................................................................................................................................
Step: #1.10


..................................................................................................................................................................................................................................

Step: #1.11




Step: #1
 https://console.firebase.google.com/?gclid=Cj0KCQjwz8bsBRC6ARIsAEyNnvqj5Reg9euAdO1kRWEZ3n3h0Kd3upZgIgbeF6aRSOe5noO9-QpMJm4aAo6OEALw_wcB




Step: #2




Step: #3





Step: #4




Step: #5






Step: #6
Enable Email and password




Step: #7





Step: #8



Step: #9




Step: #10



Step: #11

Step: #12

Step: #13




Step: #14
. firebase install
    yarn ad firebase






Step: #15

Step: #16

Step: #17

Step: #18
Step: #19
Step: #20

















Thursday, August 22, 2019

React Interview Questions

Q: Functional vs Class-Components in React?

The simplest way to define a component in React is to write a JavaScript function:
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
......................................................................................................................................................................................................................
But we can also use the ES6 class syntax to write components.
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
Both versions are equivalent and will give us the exact same output.

When should I use a function and when a class?
Syntax

A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element.
1. we cannot use setState() in our component.
2. Another feature which we cannot use in functional components are lifecycle hooks.

So why should I use functional components at all?

1. Functional component are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks
2. You end up with less code
3.They help you to use best practices. 
4. It will get easier to separate container and presentational components because we need to think more about our component’s state if we don’t have access to setState() in our component
The React team mentioned that there may be a performance boost for functional component in future React versions

No this Keyword
No Class Needed

Enforced Best Practices
Stateless functional components are useful for dumb/presentational components.
 Presentational components focus on the UI rather than behavior,
so it’s important to avoid using state in presentational components.
Instead, state should be managed by higher-level “container” components, or via Flux/Redux/etc. Stateless functional components don’t support state or lifecycle methods.
This is a good thing. Why? Because it protects from laziness.
Since stateless functional components don’t support local state,












A class component requires us to extend from React.Component and create a render function which returns a React element.



.....................................................................................................................................................................................................................................
Hooks

What are Hooks?
>> A Hook is a Special function.
>> Introduced in React 16.8.
>> Use State and other React features without writing a class
>> Hooks don't work inside classes.

Why use React Hooks
>> Avoid the confusion of this keyword and bind this.
>> Complex components become hard to understand.
>> Hooks make it easy for you to test


>>  unlike this.state
>>  you can use state Hooks more than once in a single component
like
only once
this.state ={
name:"",
city:""
}

const [name, setName]=useState()
const [City, setCity]=useState()

Rules of Hooks
>> Call at the top level, Don't call Hooks inside loops, conditions, or nested functions
>> Call from React function components ,
Don't call Hooks from regular JavaScripts functions

plugin are available follow or not hooks
eslint-plugin-react-hooks

types of Hooks mainly two importants
State Hooks: useState
Effect Hooks: useEffect

const [count, setCount]= useState(0)
call this function useState()
pass the initial State inside it
like
useState(initialState)
return an array is to be two  items
1. First is state variable which will be create
2. and second one function that can be used to set the state


.............................................................................................................................................................................................................................................

#useEffect

Operations like data fetching, subscriptions, or manually

changing the DOM from React Component are "Side Effect" or "effect"

>> It serves the same purpose as  componentDidMount, componentDidUpdate, componentWillUnmount
>> Can use multiple useEffect() in component

When is useEffect() called?
>> Initail render
>> State changes
>> Component unmounts

clean up
>> Effect that donot require cleanup
>> It's important to cleanup to avoid memory leak
>> If our effect returns a function, React runs it on unmounts
and re-render for clean up.


skipping Effect for performance optimization

>> Skip applying an effect if certain values haven't
changed between re-render
>> Pass an array as an optional second argument to useEffect

>> pass an Empty array([]), If you want to run an effect
and clean it up only once(on mount and unmount)

example as below!

Example : #1
src/component/MyChild 

import React, { useEffect } from 'react'
const MyChild = () => {
    useEffect(() => {
        console.log('initial render: mounted')
        return () => {
            console.log('clean up!:unmounted')
        }
    })

    return (
        <>
            <h1>hello</h1>
        </>
    )
}
export default MyChild

.............................................................................................................................................................................................................
import React, { Component, useState } from 'react'
import MyChild from '../src/components/Child'

const Home =()=>{
  const [showItem, setShowItem]=useState(false)

  console.log(showItem)

  return(
    <>
    <button onClick={()=>setShowItem(!showItem)}>toggle</button>
    {showItem? <MyChild/>:''}
    </>
  )
}

export default class App extends Component {
  render() {
    return (
      <>
      <Home/>
      </>
    )
  }
}


.........................................................................................................................................................................................................
A guide to useState in React

useState is a hook that allows you to have state variables in functional components.

There are two types of components in React,

  • class components.
  • functional components
Class components are ES6 classes that extend from React.Component and can have state and lifecycle methods:

class Message extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: ‘’ 
    };
  }
  componentDidMount() {
    /* ... */
  }
  render() {
    return <div>{this.state.message}</div>;
  }
}

Functional components are functions that just accept arguments as the properties of the component and return valid JSX:

function Message(props) {
  return <div>{props.message}</div>
}
// Or as an arrow function
const Message = (props) =>  <div>{props.message}</div>
As you can see, there are no state or lifecycle methods.


















Rules of Hooks

. Only call Hooks at the top level
. Do not call Hooks inside loops, conditions or nested functions

import React, {useState} from 'react'
const App = () => {
  if(true){
    useState()
  }
  return (
    <div>
      <h4>Hey</h4>
    </div>
  )
}
export default App

..............................................................................................................................................................................................................................
Hooks Programming  
with previous state (ie c=>c+1)

import React, { useState } from 'react'
const App =()=>{
  const [count, setCount] =useState(0)
  return(
    <>
    <button onClick={()=>setCount(c=>c+1)}>Click{count}</button>
    </>
  )
}
export default App
..............................................................................................................................................................................................................................
import React, { useState } from 'react'
const App = () => {
  const [{ count1, count2 }, setCount] = useState({ count1: 10, count2: 20 })
  return (
    <>
    <button onClick={() => setCount(currentState => ({ count1: currentState.count1 + 1, count2: currentState.count2 + 1 }))}>Click{count1}-{count2}</button>
    </>
  )
}
export default App
...........................................................................................................................................................................................................................
import React, { useState } from 'react'
const App = () => {
  const [count1, setCount1] = useState(20)
  const [count2, setCount2] = useState(20)
  return (
    <>
      <button onClick={() => {
        setCount1(currentState => currentState + 1)
        setCount2(currentState => currentState + 1)
      }}>Click{count1}-{count2}</button>
    </>
  )
}

export default App
..........................................................................................................................................................................................................................
Simple Form

import React, { useState } from 'react'
const App = () => {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")

  const onSubmit = (event) => {
    event.preventDefault()
    console.log(email, password)
  }

  return (
    <>
      <form onSubmit={onSubmit}>
        <input
          type="text"
          name="email"
          value={email}
          onChange={(email) => setEmail(email.target.value)}
        />
        <br></br>
        <input
          type="password"
          name="password"
          value={password}
          onChange={(password) => setPassword(password.target.value)}
        /><br></br>
        <button type='submit'>Submit</button>
      </form>
    </>
  )
}
export default App
................................................................................................................................................................................................................................

import React, { useState } from 'react'

const App = () => {
  const [values, handleChanges] = useState({ email: '', password: '' })

  const onSubmit = (event) => {
    event.preventDefault()
    console.log(values)
  }
  const handleChange=(e)=>{
    handleChanges({...values, [e.target.value]:e.target.name})
  }

  return (
    <>
      <form onSubmit={onSubmit} autoComplete="off">
        <input
          autoComplete={true}
          placeholder='Enter email'
          type="text"
          name="email"
          value={values.email}
          onChange={handleChange}
        />
        <br></br>
        <input
          autoComplete={true}
          type="text"
          name="password"
          placeholder="password"
          value={values.password}
          onChange={handleChange}
        /><br></br>
        <button type='submit'>Submit</button>
      </form>
    </>
  )
}

export default App
........................................................................................................................................................................................................................






.................................................................................................................................................................................................................................







.................................................................................................................................................................................................................................








.................................................................................................................................................................................................................................
React Native






In React Native, there is no DOM here we use Native Components which are provided by platforms such as iOS and Android.

In React Native there are no web views here, such as ionic uses web view for the application.

Basic or Core components – View, Text, Image, ScrollView, TextInput , StyleSheet etc.

List components – FlatList and SectionList.

User Interface or Form Control components: Picker, slider, button, switch.

iOS Specific Components: ActionSheetIOS, SegmentedControlIOS, AlertIOS, PushNotificationsIOS.

Android Specific components: DatePickerAndroid, TimePickerAndroid, ViewPagerAndroid, ToastAndroid, PermissionsAndroid.

Other important components: Alert, Animated, CameraRoll, Dimensions, Clipboard, StatusBar, Linking, Keyboard, ActivityIndicator, WebView, and Modal, etc.

















.................................................................................................................................................................................................................................


.................................................................................................................................................................................................................................
Why can't browsers read JSX?

React uses JSX(JavaScript extensions) that allows us to write JavaScript that looks like HTML.
But given JSX is not valid JavaScript. web browser cann't read it directly.
So, if JavaScript files contain JSX. that file will have to be transpired.
you  need a transpiler to convert your JSX
to regular JavaScript that browsers can underStand.
The most widely used transpiler right now is Babel.

.................................................................................................................................................................................................................................
What do you understand from "In React, everything is a component"

Components are the building blocks of a React application's UI.
These components split up the entire UI into small independent and reusable pieces.
Then it renders each of these components independent of each other without affecting the rest of the UI.


.................................................................................................................................................................................................................................
List Some of the React's significatns benefits.

It increases the applications's performance, Utilizing a virtual DOM diff techniques
React JS know when and what specific parts of the DOM tree exactly
to re-render or when and specific parts of DOM to ignore because
virtual DOM detects when and which the data has changed.
This makes the React app react fast.
A UI that reacts promptly is crucial in enhancing the user experience


.................................................................................................................................................................................................................................
What is use of platform module in React Native?

React Native Platform module is used to detect the platform of device in which the application is running. You can use the below code detect platform in React Native.

import {Platform, StyleSheet} from 'react-native';
const styles = StyleSheet.create({
  height: Platform.OS === 'ios' ? 200 : 100,
});

.................................................................................................................................................................................................................................







What are Flutter & React Native?
Flutter and React Native are both cross-platform mobile development frameworks. React Native was developed by Facebook and was initially released in May 2015. It was later discovered by a larger community, and ever since it has become mainly community-driven. Flutter, on the other hand, is considered as a newer framework; its first stable version was released in December 2018. Apps using React Native are written in JavaScript, while apps using Flutters are written in Dart.




Wednesday, August 14, 2019

API Key || How to hide API key in react project

API Key || How to hide API key in react project


First,  make .env file outside of your src folder.

Then, add
Prefix or Naming convention is mendatory like REACT_APP_

REACT_APP_WEATHER_API_KEY=123456
or
REACT_APP_NOT_SECRET_CODE=431644457453553
or
REACT_APP_NOT_SECRET_CODE='431644457453553'

Before commit, you should exclude this .env file so find .gitignore file and add .env.

Now you're free to go.

Don't forget to add .env in .gitignore file.

Added:

How to use env variables in your code:

const API_KEY = process.env.REACT_APP_WEATHER_API_KEY;
console.log(process.env.REACT_APP_WEATHER_API_KEY;


Note Error:-
env variable is undefined.
 How do I fix it?
In order to read env variables,
restart your server.


.......................................................................................................................................................................................................
 FaceBook Login

https://github.com/keppelen/react-facebook-login

import React, { Component } from 'react'
import FacebookLogin from 'react-facebook-login';


const BASE_URL = process.env.REACT_APP_NOT_SECRET_CODE
console.log(process.env.REACT_APP_NOT_SECRET_CODE)

class App extends Component {
  render() {
    return (
      <>
        <FacebookLogin
          appId={BASE_URL}
          autoLoad={true}
          fields="name,email,picture"
          onClick={componentClicked}
          callback={responseFacebook}

        />

      </>
    )
  }
}
export default App





























Tuesday, August 13, 2019

reactstrap

import React, { Component } from 'react'
import { Button, Container, Alert} from 'reactstrap'
export default class App extends Component {

  constructor(props){
    super(props)
    this.state={
      visibile:true
    }
  }
  toggle=()=>{
    this.setState({visibile:!this.state.visibile})
  }
  render() {
    return (
      <Container>
        <Button color='primary' active={false} block={true} onClick={this.toggle}>Submit</Button>{' '}
        <Button color='secondary'>Submit</Button>{' '}

        <Button color='danger' outline={true}>Submit</Button>{' '}
        <Button color='success' size='sm'>Submit</Button>{' '}
        <Button color='info' size='lg' outline={true}>Submit</Button>{' '}
        <Button color='warning'>Submit</Button>{' '}
        <Button color='dark'>Submit</Button>{' '}
        <Button color='light'>Submit</Button>{' '}
        <Alert color='danger' isOpen={this.state.visibile} toggle={this.toggle} size='sm' >Hello</Alert>
      </Container>
    )
  }
}

...................................................................................................................................................................................................................................
Example with Alert # 1

import React, { Component } from 'react'
import { Container, Button, Alert } from 'reactstrap'

export default class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      toggleVisible: true
    }
  }

  toggleVisibleMethod = () => {
    this.setState({ toggleVisible: !this.state.toggleVisible })
  }

  render() {
    return (
        <Container>
        <Button color='primary' onClick={this.toggleVisibleMethod}>primary</Button>
        <Alert isOpen={this.state.toggleVisible} toggle={this.toggleVisibleMethod}> Alert Here!                  </Alert>
        </Container>
    )
  }
}
.................................................................................................................................................................................................................................
Example with Modal #2

import React, { Component } from 'react';
import { Container, Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';

class App extends Component {
  state = {
    modalIsOpen: false
  }

  toggleModal = () => {
    this.setState({
      modalIsOpen: !this.state.modalIsOpen
    });
  }

  render() {
    return (
      <Container>
        <Button color="primary" onClick={this.toggleModal}>Open Modal</Button>

        <Modal isOpen={this.state.modalIsOpen}>

          <ModalHeader toggle={this.toggleModal}>Modal Title</ModalHeader>

          <ModalBody>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi rem fugiat perspiciatis sint, nostrum labore nobis quidem sed impedit quae quisquam corrupti, libero commodi a quod pariatur quo qui. Id?</ModalBody>

          <ModalFooter>
            <Button color="primary">Sign Up</Button>
            <Button color="secondary" onClick={this.toggleModal}>Cancel</Button>
          </ModalFooter>

        </Modal>
      </Container>
    );
  }
}

export default App;




..

Sunday, August 11, 2019

Warning: componentWillMount is deprecated and will be removed in the next major version. Use componentDidMount instead. As a temporary workaround, you can rename to UNSAFE_componentWillMount.

Warning: componentWillMount is deprecated and will be removed in the 
next major version. Use componentDidMount instead. 
As a temporary workaround, you can rename to UNSAFE_componentWillMount.

Please update the following components: Container, 
Image, ResourceSavingSceneView, TabViewPagerPan, TouchableOpacity, 
Transitioner, withCachedChildNavigation(TabView)

Learn more about this warning here:
https://fb.me/react-async-component-lifecycle-hooks
............................................................................................................................................................................................................................................

Solutions

import { YellowBox } from 'react-native';

YellowBox.ignoreWarnings([
 'Warning: componentWillUpdate is deprecated',
 // 'Warning: componentWillMount is deprecated',
//  'Warning: componentWillReceiveProps is deprecated',
]);

Friday, August 2, 2019

java.io.IOException: Access is denied

java.io.IOException: Access is denied



Solutions: #1
android==>build.gradle==>gradle.properties



org.gradle.jvmargs=-Xmx4608M

like this

C:\Users\sapan\Desktop\React Native\demorn1\android>.\gradlew.bat clean