Skip to content

Instantly share code, notes, and snippets.

@ishanajmeri
Last active June 3, 2020 13:38
Show Gist options
  • Save ishanajmeri/cfedd7fff8b6abc1ad8b76098df954bf to your computer and use it in GitHub Desktop.
Save ishanajmeri/cfedd7fff8b6abc1ad8b76098df954bf to your computer and use it in GitHub Desktop.
Spots of react JS
  • imrc
  • cc
  • start
  1. create-react-app folder_name
  2. In index.js add bootstrap
import 'bootstrap/dist/css/bootstrap.css';
import 'font-awesome/css/font-awesome.css';
  1. Go to app.js 4.create home component and start.
  • Map is a data collection type.This method used to traverse in the components of objects.(javascript function)
  • Filter method creates a new array with with all elements that pass the test implemented by the provided function.
  • To kill or stop the localhost, In terminal
[sudo lsof -i:3000] [sudo killall -9 node] .
  • [....] spread notation. Add items of array into object.
  • Lodash is a JavaScript library which provides utility functions fo common programming tasks.
  1. _.range
  2. _.orderBy
  3. _.get
  • PropTypes defines types of the components that we are using in application.(checking types)
  • React Js is a Javascript Library where you can develop and run faster web applicatons using React.
  • React-Native is a framework.
  • Routing is the process of moving packets across a network form one host to a another.Routing is the process of selectin ga path for traffic in a network or between or acros multiple networks.
  • DOM Document Object Model.
  • A router allows your application to navigate between different components,changing the brower URL,modifying the browser history, and keeping the UI state in sync with the URL.
  • Using switch, like with "to".
  • Use of queryString for searching URL.
  • Use of redirect for not-found page and go to another page.
  • push and replace for go to one page to another page.
  • To add tag outside some content : shift + ctrl + p ,,,wrap,,,,and write outsider tag.
  • [createRef] ,,,It is provide a way to access DOM nodes or React elements created in the render method.when a ref is passed to an element in render, a reference to the node becomes accessible at the [current] attribute of the ref.
  • The [currentTarget] read-only property of the event interface identifies the current target for the event.
  • Use of joi for form username and password something stuff design and looks.
  • React is simple a lightweight library for building UIs.
  • An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.
  • jwt(json web token
  • use of [.header("access-control-expose-headers", "x-auth-token")] for token of data. In file [user.js].
  • [window.location="/path" ] for full reload of site.
  • Hide component.
  • [target="_blank"] attribute use in <a> tag. It will open new tab for link of the <a> tag.
  • When you add a rel="noopener" attribute into your code,it prevents the new page from being able to access the window.opener property and will make it run in a separate process. noopener tag woks as a security fix which prevents malicious links to take control over an opened tab.
  • rel="noreferrer" is used to hid source of the traffic going from the website towards another website.
  • use of <svg> tab for draw graphical thing .With attribute width ,height and viewBox and <path> tab.
  • [ e.preventDefault()] This method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
  • [.push ] for adding element in const.example,,
const constName = [];
constName.push('element');
  • For creating an array in states.
    state = {
      object: Array(number),
    };
  • For adding contibution on Github, Write in terminal
    git commit -m ' message'
    git push
    
  • If you send the values of states to the component through props, you can't change that values in that component file because it's props values are constent in it.
  • mouse hover to pointer write in tag
    style={{cursor:"pointer"}}
  • collect value outside of array :
    const lines = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
    ];
    const [a, b, c] = lines[2];
  • List of propTypes:
    const types = [array, bool, func, number, object, string, symbol];
  • To see which origin exists, in terminal
    git remote -v
    
  • Adding input upload in Button
<input
  accept="image/*"
  display='none'
  id="contained-button-file"
  multiple
  type="file"
/>
<label htmlFor="contained-button-file">
  <Button variant="contained" color="primary" component="span">
    Upload
  </Button>
</label>

CurrentTarget Event Property

  • The currentTarget event porperty returns the element whose event listenrs triggered the event.This is particularly useful during capturing and onChange state changing.
handleChange = ({ CurrentTarget: input }) => {
  consol.log(input);
};
<input
  type="text"
  name="name"
  value="value"
  onChange={this.handleChange}
></input>;

// on console:
// <input type="text" name="name" value="value"></input>

npm contentful

  • The content Delivery API is a read-only API for delivering content from contentful to app, websites and other media.
  • Initialize the client :
  var client = contentful.createClient({
    space: '<space_id>',
    accessToken: '<access_token>'
  })

axios

  • To get data from backend in Lifecycle Hooks i.e
componentDidMount(){
  const promis = axios.get('url')
}
  • requests of axios :
axios
  .get('url')
  .then(function (respose) {
    //handle success
  })
  .catch(function (error) {
    //handle errors
  });

unfetch

  • same as the axious.
npm i unfetch
  • To get data from backend in Lifecycle Hooks, we can also use getInitialProps to the main function in file.
app.getIntialProps = async function () {
  const data = await fetch('url'); // compare to the componentDidMount(){}
};
  • requests of fetch :
const data = await (await fetch('url')).json();

context or context API

  • React's context allows you to share information to any components, without any help of props.
  • Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Create file of context.jsx in root path

  • context component:
const Context = React.createContext();
  • There are two export component :
  1. class Provider

For adding in root file App.js
Changing state by using the dispatch redux property

export class Provider extends Component{
  state={
    data:[]
    dispatch:action => this.setState(state => reducer(state,action)) // you have to define or use this element in other file with the same 'type' component in it and after that help of payload we can change the state.
  };
  componentDidMound(){
    //if you want ot change state in file by 'setState'
  }
  render(){
    return (
      <Context.Provider value={this.state}>
      {this.props.childern}
      </Context.Provider>
    );
  }
}

reducer component:

const reducer = (state, action) => {
  switch (action.type) {
    case 'objcet_in_type':
      return {
        ...state,
        data: action.payload, // payload is the change data that comes from the another file where the 'Consumer' used.
      };
    default:
      return state;
  }
};
  1. const Consumer

For adding in file where we can use the states or values that provide by the provider.

export const Consumer = Context.Consumer;
  • When you write Consumer in other file, you can use the state value of class Provider in that file.
<Consumer>
  {(value) => {
    const { elemen_of_Provider_class } = value;
    return <div></div>;
  }}
</Consumer>

React UI libraries

  1. Ant Design
  2. Chakra UI
  3. Tailwind UI
  4. Semantic UI
  5. Material UI
  6. React Bootstrap
  7. bulma
  8. onsen UI
  9. blueprint
  10. argon design system react
  11. shards react

animations in React

  1. react-motion
  2. react-spring
  3. Framer Motion

flux

  • Flux is mainly an application architecture cencept deveploped by Facebook, but the same term also refers to a library that represetnts the offical implementation.
  • Flux braks down into four major parts:actions, the dispatcher,stores, and views:
    • Actions decscribe an action that took place in the application.
    • The dispatcher is a singleton registry of callbacks.It acts as a middleaman by passing the actions to all the stores that subscribed to it.
    • Stores manage the state and logic needed to update it for spcific parts of the application.
    • Views are plain old React components.

Using the state Hook

  • We can use usestate for declare new state
const [state,Setstate(function)] = useState(initialState);
// example
function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Next.js

  • Next.js is React based framework.
  • Script :
"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  • In nextjs, It is client-side navigation.The action takes place in the browser, without making a request to the server.
  • The only special directories are /pages and /public.
  • page :
    • A page is a React component exported from a .js file in the pages directory.Each page is associated with a route based on its file name.
    • Add brackets to a page('[param]') to create a dynamic route.ex:
    pages/post/[pid].js
    

Main Features:

  1. Hot Code Reloading : It automatically reloads the application when changes in the code get saved.
  2. Automatic Code splitting : By this feture, every import in the code get bundled and served with each page.It means that unnecessary code never get loaded on the page.
  3. Ecosystem Compatibility : Compatible with JavaScript,Node and react.
  4. Server Rendering : Easily render react component on server before sending HTML to client.

Link

<Link href="" as="">
  {name}
</Link>
<Link href={{ pathname: '/about', query: { name: 'ZEIT' } }}> // /about?name=ZEIT

router

Router
import Router from 'next/router';
  1. Router.push(url,as,options)
  • options - shallow: Update the path of the current page without rerunning getInitialProps.Defaults to false.
  1. Router.replace(url,as,options)

  2. Router.beforePopState(({url, as, options}) : () => Boolean)

  3. Router.events

UseRouter & withRouter
import { withRouter, UseRouter } from 'next/router';
  • By this we can use 3 router objects returned by useRouter.
  1. pathname: String- current route.
  2. query: object - The query string parsed to an object.
  3. asPath : string - Actual path shown in the browser.

CSS

<style jsx>{`
  //all CSS components
`}</style>

SWR

  • SWR : stale-while-revalidate
  • SWR is a React Hooks library for remote data fetching.It first returns the data from cache(stale), then sends the fetch request(revalidate), and finally comes with the up-to-date data again.
useSWR
import useSWR from 'swr';
  • The React Hook useSWR accepts a key and a fetch function. key is a unique identifier of the data, normally the URL of the API. Then key will be passed to fetch, which can be any asynchronous function which returns 2 values:data and error,based on the status of the request.
function fetcher(url) {
  return fetch(url).then((r) => r.json());
}
function something() {
  const { data, error } = useSWR(
    'url of the file from data will come',
    fetcher
  );
  const author = data?.author;
  let quote = data?.quote;

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  return <div>hello {data.name}!</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment