Skip to content

Instantly share code, notes, and snippets.

@rjoydip-zz
Last active August 11, 2018 16:32
Show Gist options
  • Save rjoydip-zz/b20cabb491da8b734a6ffdc00b81555b to your computer and use it in GitHub Desktop.
Save rjoydip-zz/b20cabb491da8b734a6ffdc00b81555b to your computer and use it in GitHub Desktop.

React.js Question Answers

What is react.js?

A JavaScript library for building user interfaces

What is the role of webpack?

Webpack is a popular module bundling system built on top of Node.js. It can handle not only combination and minification of JavaScript and CSS files, but also other assets such as image files (spriting) through the use of plugins.

With Webpack, you give a single path. The path to your entry point. This is typically index.js or main.js. Webpack will now investigate your application. It will figure out how everything is connected through require, import, etc. statements, url values in your CSS, href values in image tags, etc. It creates a complete dependency graph of all the assets your application needs to run. All of this just pointing to one single file.

An asset is a file. It being an image, css, less, json, js, jsx etc. And this file is a node in the dependency graph created by Webpack.

  |---------|         |------------|       |--------|
  | main.js | ------- | styles.css | ----- | bg.png |
  |---------|    |    |------------|       |--------|
                 |
                 |    |--------|       |-------------|
                 |--- | app.js | ----- | config.json |
                      |--------|       |-------------|

When Webpack investigates your app, it will hook on new nodes to the dependency graph. When a new node is found, it will check the file extension. If the extension matches your configuration, it will run a process on it. This process is called a loader. An example of this would be to transform the content of a .js file from ES6 to ES5. Babel is a project that does this and it has a Webpack loader. Install it with npm install babel-loader.

import path from 'path';

const config = {

  // Gives you sourcemaps without slowing down rebundling
  devtool: 'eval-source-map',
  entry: path.join(__dirname, 'app/main.js'),
  output: {
    path: path.join(__dirname, '/dist/'),
    filename: '[name].js',
    publicPath: '/'
  },
  module: {
    loaders: [{
      test: /\.js?$/,
      exclude: /node_modules/,
      loader: 'babel'
    }]
  }
};

We basically tell Webpack that whenever it finds a .js file it should be passed to the Babel loader.

What is the role of bable in react?

Facebook keeps React up to date, even made it compatible with ES6. But as we know not all browsers support all the properties of ES6. So we use Babel for this purpose. Babel compiles the ES6 code into ES5 code so that it can run in the old browser.

To setup install the following npm packages npm i -D babel-loader babel-preset-es2015 babel-preset-react

The babel-preset-es2015 and babel-preset-react are plugins being used by the babel-loader to translate ES6 and JSX syntax respectively.

As we did for Webpack, babel-loader also requires some configuration. Here we need to tell it to use the ES6 and JSX plugins.

.babelrc

{
  "presets" : ["es2015", "react"]
}

Create a .babelrc file and update it as below

The next step is telling Webpack to use the babel-loader while bundling the files

open webpack.config.js file and update it as below

module : {
  loaders : [
    {
      test : /\.jsx?/,
      include : APP_DIR,
      loader : 'babel'
    }
  ]
}

What is state and props?

State: Components data will be stored in component's State. This state can be modified based on user action or other action. when a component state is changed React will re-render the component to the browser.

Props: Most components can be customized when they are created, with different parameters. These creation parameters are called props.

What is propstypes?

PropTypes exports a range of validators that can be used to make sure the data you receive is valid. In this example, we’re using PropTypes.string. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons, propTypes is only checked in development mode.

import PropTypes from 'prop-types';

class MyComponent extends React.Component {
  render() {
    // This must be exactly one element or it will warn.
    const children = this.props.children;
    return (
      <div>
        <h1>Hello, {this.props.name}</h1>
        {children}
      </div>
    );
  }
}

MyComponent.propTypes = {
  name: PropTypes.string,
  children: PropTypes.element.isRequired
};

How to set default props?

You can define default values for your props by assigning to the special defaultProps property:

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

// Specifies the default values for props:
Greeting.defaultProps = {
  name: 'Stranger'
};

// Renders "Hello, Stranger":
ReactDOM.render(
  <Greeting />,
  document.getElementById('example')
);

Can we pass data to a component without using props?

Yes, by using children. There is a children property in props.

class Greeting extends React.Component {
  render() {
    return (
      {this.props.children}
    );
  }
}

// Specifies the default values for props:
Greeting.defaultProps = {
  name: 'Stranger'
};

// Renders "Hello, Stranger":
<Greeting>
  <p>This isa greeting paragraph</>
</Greeting>

How to call a function on button clicked?

There are two ways to call a function. <button onClick={this.onButttonClickedFn.bind(this)} /> and <button onClick={() => this.onButttonClickedFn()} />

What is the difference between below example ?

onClick={this.onButttonClickedFn.bind(this)} and onClick={this.onButttonClickedFn()}

this.onButttonClickedFn.bind(this) this refer to the function and bind this (class reference) on it and this.onButttonClickedFn() execute the function imediately.

How does ReactJS update the DOM?

https://www.youtube.com/watch?v=Iw2BLUjQo1E&index=10&list=PL55RiY5tL51oyA8euSROLjMFZbXaV7skS

What is stateless component?

A stateless component is just a function which receive props. A stateless component doesn't have class, this and state.

import React from ‘react’;

const HelloWorld = ({name}) => (
 <div>{`Hi ${name}`}</div>
);

export default HelloWorld;

How to pass data from child to parent component?

In Parent Component:

getData(val){
    // do not forget to bind getData in constructor
    console.log(val);
}
render(){
 return(<Child sendData={this.getData}/>);
}

In Child Component:

demoMethod(){
  this.props.sendData(value);
}

Can we do two way binding?

Yes, But this will be painfull when multiple component comes together. This can be overcomed by using redux.

Example code: https://github.com/mschwarzmueller/reactjs-basics/tree/09-two-way-binding/src

Example tutorial: https://www.youtube.com/watch?v=IK9k9hSuYeA&index=14&list=PL55RiY5tL51oyA8euSROLjMFZbXaV7skS

What are the lifecycle methods?

https://cdn-images-1.medium.com/max/1600/1*sn-ftowp0_VVRbeUAFECMA.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment