3) Creating a basic component in React JS





Components are the most important part of react js.There are two ways to create a component
1)Component with functions
2) Component with class
Here is a detailed explanation of when to use function components and when to use class component.
A) Creating component with functions
 Here are the steps to  create component with functions
1) Create a function and  send a parameter props to it, props is an object that holds all the values that were passed when the component was rendered.
2) return the JSX which is supposed to be visible on the page.
2) In order to make the view visible , we need to render it using the statement
ReactDOM.render
3) ReactDOM render takes two parameters
   a) name of the component
   b) Where the component should be visible

Here is an example of how a basic component in react should be written

Basic Component example using simple function :

const Button = function (props){
return (
<button>{props.label}</button>
)
};
ReactDOM.render(<Button label="Submit"/>,mountNode);
          
  • The code which we are returning is not html and is jsx which will be compiled into java script
  • As "props" holds all the values that were passed when the component was rendered, we can access the label of the button with props.label 
  • The syntax to mount component in the browser is 
               ReactDom.render(<Button/>,mountNode);

As mentioned , The first argument is the component you want to render.
The second argument is the element in which the component should be rendered.Here we used mountNode which is a predefined element which displays everything inside it on the browser.

Basic component example using arrow functions:

const Button = (props) =>{
return(
    <button>Submit</button>
    );
};

ReactDOM.render(<button/>,mountNode);

B) Creating component with class

When ever we want the state of the component to be changed on adding any event Handlers , we need to re- render the component.
In above example our button is a property and we cannot change properties using function components because component properties are immutable.
The reason why  function components are immutable is that they  do not have a state.To have state , we should use class components and not function components.

 Here are the steps to  create component with classes
1) We can either use React.createClass or a class which extends React.Component
2) Add a state property in order to make changes to our component
3) Instead of directly returning the JSX code, here we will place it inside our render method
4) Any event handling methods can be wriiten inside the class itself or inside the constructor.
5) Render the component using
ReactDOM.render()


Basic component example using classes 
Title:  increment counter value on button click

class Button extends React.Component {
    //state={counter:0};
    constructor(props) {
        super(props);
        this.state = {
            counter: 0
        };
        this.handleClick = () => {
            this.setState((prevState) => {
                return {
                    counter: prevState.counter + 1
                };
            });
        }
    }


    render() {
        return ( <
            button onClick = {
                this.handleClick
            } > {
                this.state.counter
            } < /button>
        )
    };
}

ReactDOM.render( < Button / > , mountNode);

setState method in react
The setState method is a built in method in react which is available on every class component instance to update a component state.The setState code can simply be written like below

handleClick=()=>{
this.setState({
counter:this.state.counter+1
})
}

setState is an asynchronous method and when setState is called multiple times the update cycle will overwrite the previous updates, as a result , the previous changes are lost.
We have an alternative solution for this problem,instead of giving it to the new state directly,we can give it to a function which transforms the current state and props into a new state as below

this.setState((prevState) => {
                return {
                    counter: prevState.counter + 1
                };
            });
Here we are using setState as a function instead of an object which solves the problem.The function receives a prevState object and we can use it without worrying about any issue. By doing so , the function returns the correct value which we need.

Summary:

1) Whenever there is a change in state in the component we are building , we cannot use function components and should use class components.

2)In order to use the state object , we need to initialize it. We can initialize a state object either in the constructor or in the class

3) The super(props) statement used in the class is to support inheritance and make the component available to use it anywhere else in the application.

4) Use set state method to change the component.Use setState as a function as it is asynchronous


Creating a component by combing two components

Here is an example of combing two components.Here we have created two components namely result and Button.
Button component is to make the click function work , which increments  the counter
Result component is to display the value of the counter.
A component can access its own functions actions and state, to access other class functions we need to use props.

class Button extends React.Component{
// super(props);
handleClick=()=>{
this.props.onClickFunction(this.props.incrementValue);
 };
render(){//returns components jsx
return(
<button onClick={this.handleClick}>
+{this.props.incrementValue}
</button>
     );
   }
}
const Result= (props)=>{
return(
<div>{props.counter}</div>
);
};

class App extends React.Component{
state={counter:0};
incrementCounter=(incrementValue)=>{
this.setState((prevState)=>({
  counter:prevState.counter +incrementValue
})
)
};
render(){
return (
<div>
    <Button incrementValue={1} onClickFunction={this.incrementCounter}/>
    <Button incrementValue={5} onClickFunction={this.incrementCounter}/>
    <Button incrementValue={10} onClickFunction={this.incrementCounter}/>
    <Button incrementValue={100} onClickFunction={this.incrementCounter}/>
    <Result counter={this.state.counter}/>
  </div>
)
 }
}

ReactDOM.render(<App/>,mountNode);





Share this

Related Posts

Previous
Next Post »