Wednesday, October 31, 2018

TypeScripts


TypeScripts

The quickest way to start a React/TypeScript app is by using create-react-app with the TypeScript template.

npx create-react-app my-new-app --typescript
or
npx create-react-app my-app --template typescript

..................................................................................................................................................................................................................................
Third-party Libraries

yarn add @types/<package-name>

npm install @types/<package-name>
................................................................................................................................................................................................................................

Note -
npx is a command released with npm 5.2 which allows you to execute CLI commands and executables hosted by the registry — meaning global installations are no longer required.


Home.tsx
............................................................................................................................................................................................................................................


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


............................................................................................................................................................................................................................................
Components
Basic components. Let’s look at an example.

import React from 'react'
// Written as a function declaration
function Heading(): React.ReactNode {
  return <h1>My Website Heading</h1>
}

// Written as a function expression
const OtherHeading: React.FC = () => <h1>My Website Heading</h1>

Happy Coding :)
............................................................................................................................................................................................................................................
Props
The next core concept we’ll cover is props. You can define your props using either an interface or a type. Let’s look at another example.

import React from 'react'
interface Props {
  name: string;
  color: string;
}

type OtherProps = {
  name: string;
  color: string;
}

// Notice here we're using the function declaration with the interface Props
function Heading({ name, color }: Props): React.ReactNode {
  return <h1>My Website Heading</h1>
}

// Notice here we're using the function expression with the type OtherProps
const OtherHeading: React.FC<OtherProps> = ({ name, color }) =>
  <h1>My Website Heading</h1>


Happy Coding :)
............................................................................................................................................................................................................................................

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

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


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

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <Text>Open up App.tsx to start working on your app!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
......................................................................................................................................................................................................................
  Reuseable Component

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

interface Props {
}
export const Center: React.FC<Props> = ({ children }) => {
    return (
        <View style={styles.container}>
            {children}
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'

    }
})
...............................................
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Center } from './src/components/Center'

function App() {
  return (
    <Center>
      <Text> Hello Tsx Example</Text>
      <Text> Hello Tsx Example</Text>
      </Center>
  )
}
export default App

const style = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  }
})
Happy Coding :)
.................................................................................................................................................................................................................................
App.tsx

Example #2 [ Functional Component ]

import * as React from 'react';

interface IProps {
  name?: string;
}

const Header: React.FC<IProps> = (props: IProps) => (
  <h1>Hello, {props.name}! Welcome to React and TypeScript.</h1>
);

Header.defaultProps = {
  name: 'world',
};

export default Header;

name?. We will make the name optional, so we indicate that with a ?. Marking a key as optional means that its type can be either string | undefined.


React.FunctionComponent
or
SFC
or
React.FC<Props>

Happy Coding :)
.................................................................................................................................................................................................................................
Example #3

import * as React from 'react';

interface IProps {
  countBy?: number;
}

interface IState {
  count: number;
}

class App extends React.Component<IProps, IState> {
  public static defaultProps: Partial<IProps> = {
    countBy: 1,
  };

  public state: IState = {
    count: 0,
  };

  public increase = () => {
    const countBy: number = this.props.countBy!;
    const count = this.state.count + countBy;
    this.setState({ count });
  };

  public render() {
    return (
      <div>
        <p>My favorite number is {this.state.count}</p>
        <button onClick={this.increase}>Increase</button>
      </div>
    );
  }
}

export default App;


Note
The increase function is used to increment the counter. The countBy is extracted as
const countBy: number = this.props.countBy!,
The exclamation mark ! indicates to TypeScript that we know the value will exist and to not throw a potential undefined error.
Finally we create the HTML to wire up the component.

Happy Coding :)
.................................................................................................................................................................................................................................
Example #4

import React from 'react'

type CardProps = {
  title?: string,
  paragraph?: string     // the paragraph is optional
}
// No need to define the defaultProps property

const App: React.FC<CardProps> = ({ title,paragraph = 'Hello World' }) => {
  return (
    <div>
     <h4>{title}</h4>
      <p>
        {paragraph}
      </p>
    </div>
  )
}

export default App

Happy Coding :)
.................................................................................................................................................................................................................................
Example #5 [ useState ]

import React, { useState } from 'react';
const App: React.FC<{ initilaValue?: number }> = ({ initilaValue = 10 }) => {
  const [count, setCount] = useState(initilaValue)
  return (
    <>
      <h3>{count}</h3>
      <button onClick={() => setCount(count => count + 1)}>Increment</button>
    </>
  )
}
export default App
Happy Coding :)
.................................................................................................................................................................................................................................
Example #6 [ Functional Components ]
Stateless or functional components can be defined in TypeScript like so,
import * as React from 'react';

const App: React.FunctionComponent<{count?: number}> = (props) => {
  return <h1>{props.count}</h1>;
};

export default App;

Happy Coding :)
.................................................................................................................................................................................................................................
Example #7

import * as React from 'react';
interface Props {
  count?: number;
}
const App: React.FC<Props> = (props) => {
  return <h1>{props.count}</h1>;
};
export default App;


Happy Coding :)
.................................................................................................................................................................................................................................
Example #8

import React from  'react';
interface Props {}

interface State {
  count: number;
};

export default class App extends React.Component<Props, State> {
  state: State = {
    count: 0
  };

  increment = () => {
    this.setState({
      count: (this.state.count + 1)
    });
  };

  decrement = () => {
    this.setState({
      count: (this.state.count - 1)
    });
  };

  render () {
    return (
      <div>
        <h2>{this.state.count}</h2>
        <button onClick={this.increment}>Increment</button>
        <button onClick={this.decrement}>Decrement</button>
      </div>
    );
  }
}


Happy Coding :)
.................................................................................................................................................................................................................................
Example #9

import * as React from 'react';

interface Props {
  count?: number;
}

export default class Count extends React.Component<Props> {
  static defaultProps: Props = {
    count: 10
  };

  render () {
    return <h1>{this.props.count}</h1>;
  }
}


Happy Coding :)
.................................................................................................................................................................................................................................
Example #10



Happy Coding :)
.................................................................................................................................................................................................................................



























Wednesday, October 24, 2018

Couldn't find preset "module:metro-react-native-babel-preset" relative to directory

Configuring Jest in React Native 0.57.0

I'm trying to get a baseline React Native app setup. Unfortunately, I kept running into problems with configuring Jest. When I run yarn test, I'd get this failure:

Error
C:\Users\sapan\Desktop\react native\Hello>npm test

> Hello@0.0.1 test C:\Users\sapan\Desktop\react native\Hello
> jest

 FAIL  __tests__/Home.js
  ● Test suite failed to run

    Couldn't find preset "module:metro-react-native-babel-preset" relative to directory "C:\\Users\\sapan\\Desktop\\react native\\Hello"

      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
          at Array.map (<anonymous>)
      at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)      at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)
      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.402s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

Solution

the jest section of package.json should look like this:

  "jest": {
    "preset": "react-native",
    "transform": { "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js" }
  }


"jest": {
"preset": "react-native",
"transform": { "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js" }

}













JSON Data Fetch in Custom way

JSON Data Fetch in Custom way  


Data.js

export const Book = [
    {
        id: 1,
        name: "JavaScript",
        price: 200
    },{
        id: 2,
        name: 'React Native',
        price: 2000
    },
    {
        id: 3,
        name: "Node.js",
        price: 40
    }

]

_____________________________________________________________________________

App.js


import React, { Component } from 'react';
import { View, Text, FlatList } from 'react-native';
import { Book } from './Data'

//Custom Component 

class Custom extends Component{
  renderData = data=>{
    return data.map((item, index)=>{
      return<View key={index}>
        <Text>{item.id}-{item.name}</Text>
      </View>
    })
  }
  render(){
    return(
      <View>
      {this.renderData(this.props.data)}
      </View>
    );
  }
}


class Home extends Component {
  render() {
    return (
      <View>
       <Custom data={Book}/>
      </View>
    );
  }
}
export default class App extends Component {
  render() {
    return (
      <View>
        <Home/>
      </View>
    );
  }
}








...................................................................................................................................................................................................................................
Example : # 2 [GET]

import React, { Component } from 'react'
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      items: []
    }
  }
  componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json()) //<-- json format
      .then(responseJson => {
        this.setState({
          loading: true,
          items: responseJson
        })
      })
  }

  render() {
    var { loading, items } = this.state
    if (!loading) {
      return <div>Loading...</div>
    } else {
      return (
        <div>
          <ul>
            {items.map(item => (
              <li key={item.id}>
                Name: {item.name} | Email: {item.email}
              </li>
            ))}
          </ul>
        </div>
      )
    }
  }
}
export default App
................................................................................................................................................................................................................................
Example : # 3[POST]

import React, { Component } from 'react'

class App extends Component {
  async PostData() {
    try {
      let result = await fetch('https://webhook.site/1544ea3e-30c2-416f-b8c5-15c712cc739e', {
        method: 'post',
        mode: 'no-cors',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Charset':'utf-8'
        },
        body: JSON.stringify({
          key1: 'myusername',
          email: 'mymail@gmail.com',
          name: 'Johan',
          lastname: 'Doe',
          age: 12
        })
      })
      console.log('Results: ' + result)
    } catch (e) {
      console.log(e)

    }
  }

  render() {
    return (
      <div>
        <h1>Post Data</h1>
        <button onClick={() => this.PostData}>Press Me to Post Data</button>
      </div>

    )
  }
}
export default App


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













Loading Screen


Example : #1
import React, { Component } from 'react'
import { View, Text, StyleSheet } from 'react-native'

class MainService {
  static load(cb) {
    setTimeout(cb, 2000)
  }
}

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: false
    },
      MainService.load(()=> this.setState({ isLoading: true }))
  }
  render() {
    return (
      <View>
        {this.state.isLoading ? <Text>Welcome</Text>:<Text> Loading..... </Text>}
      </View>
    )
  }
}
export default App
..............................................................................................................................................................................................................................
Example : #2

import React, { Component } from 'react'
import { View, Text, ActivityIndicator } from 'react-native'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: true
    }
  }
  componentDidMount() {
    setTimeout(()=>this.setState({isLoading:false}),5000)
  }

  renderLoading() {
    return (
      <View>
        <ActivityIndicator size='large' color='red' animating></ActivityIndicator>
      </View>
    )
  }
  render() {
    return (
      <View>
        {this.state.isLoading ? this.renderLoading() : null}
      </View>
    )
  }
}
export default App


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

Example : #3

...................................................................................................................................................................................................................................
Example : #4

...................................................................................................................................................................................................................................
Example : #5

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



Error:Could not resolve all files for configuration ':app:debugCompileClasspath'.

Error:Could not resolve all files for configuration ':app:debugCompileClasspath'.



Answer: Moving the google() to the top of the repositories fixed issue.

let me know , How do that
android --> build.gradle 

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 27
        supportLibVersion = "27.1.1"
    }
    repositories {
        google()              
        jcenter()
        
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()           
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        
    }
}


task wrapper(type: Wrapper) {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}