function component and class component in react code example
Example 1: function inside a class component react
export default class Archive extends React.Component {
saySomething(something) {
console.log(something);
}
handleClick(e) {
this.saySomething("element clicked");
}
componentDidMount() {
this.saySomething("component did mount");
}
render() {
return ;
}
}
Example 2: class to functional component react
// convert a class component to a functional component
class MyComponent extends React.Component {
state: {
name: 'Bob'
}
render() {
return (
Hello, my name is {this.state.name}
);
}
}
const MyComponent = () => {
const [name, setName] = React.useState('Bob');
return (Hello, my name is {name}
);
}