Home > Software engineering >  How to convert class components to functional component in react?
How to convert class components to functional component in react?

Time:08-14

How can I convert this section of code to react functional component? It is a really old section of code and I have to convert it in functional component. Need to know the standard way of doing it.

import React from 'react';
import { Button, Container, Row, Col } from 'reactstrap';
import {Redirect} from 'react-router-dom';

export class ClickPhoto extends React.Component{

    constructor(props){
        super(props);
        this.state={
            clickPhoto:false
        }
        this.handle=this.handle.bind(this);
    }
    handle(){
        sessionStorage.setItem('/camera',JSON.stringify(true));
        sessionStorage.setItem(this.props.current,JSON.stringify(false));
        this.setState({
            clickPhoto:true
        })
    }
    render(){
        if(this.state.clickPhoto===true){
            return <Redirect to="/camera"/>
        }
        else{
            return (
                <div className="text-center" style={{marginTop:"15px",marginBottom:"15px"}}>
                <Container className="clickPhoto">
                    <Row>
                        <Col><Button color="success" onClick={this.handle}>CLICK PHOTO</Button></Col>
                    </Row>
                </Container>
                </div>
            );
        }
    }
};
```

CodePudding user response:

You can write functional component as follows

import React, {useState} from 'react';
...
const ClickPhoto = (props) => {
  const[clickPhoto, setClickPhoto] = useState(false);

  const handle = () =>{
    sessionStorage.setItem('/camera',JSON.stringify(true));
    sessionStorage.setItem(this.props.current,JSON.stringify(false));
    setClickPhoto(true);
  }

  return clickPhoto ? (<Redirect to="/camera"/>)
  : (
    <div className="text-center" style={{marginTop:"15px",marginBottom:"15px"}}>
    <Container className="clickPhoto">
        <Row>
            <Col><Button color="success" onClick={handle}>CLICK PHOTO</Button></Col>
        </Row>
    </Container>
    </div>
);

}

CodePudding user response:

Here are the steps:

  1. use function instead of class
  2. remove the constructor
  3. remove the render() method, keep the return
  4. add const before all methods
  5. remove this.state throughout the component
  6. remove all references to ‘this’ throughout the component
  7. Set initial state with useState()
  8. change this.setState() … instead, call the function that you named in the previous step to update the state…
  9. replace compentDidMount with useEffect
  10. replace componentDidUpdate with useEffect
  • Related