Reputation: 123
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>
);
}
}
};
```
Upvotes: 0
Views: 1267
Reputation: 801
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>
);
}
Upvotes: 3
Reputation: 174
Here are the steps:
Upvotes: -1