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:
- use function instead of class
- remove the constructor
- remove the render() method, keep the return
- add const before all methods
- remove this.state throughout the component
- remove all references to ‘this’ throughout the component
- Set initial state with useState()
- change this.setState() … instead, call the function that you named in the previous step to update the state…
- replace compentDidMount with useEffect
- replace componentDidUpdate with useEffect