Reputation: 527
I am very new to react.js. I need to implement constructor and more functions which I am aware in Class. So below are the code I want to convert Arrow function to Class. Please help I am very very new to React.js
const CreateArea = () => {
const [content, setContent] = useState('')
function onSubmit(e){
e.preventDefault()
var date = moment().utcOffset('+05:30').format('hh:mm A DD-MM-YYYY');
firebase.firestore().collection('qna').add(
{
title: "James",
content,
time: new Date(),
time2: date,
status: "0"
})
.then(() => {
setContent('')
swal({
title: "Question Submitted!",
text: "Your Question is waiting for Approval.",
icon: "success",
button: "Close",
});
})
}
return (
<div id="footer">
<form onSubmit={onSubmit}>
<textarea
name="content"
onChange={e => setContent(e.currentTarget.value)}
value={content}
placeholder="Enter Your Question"
rows="2"
required
/>
<button></button>
</form>
</div>
);
}
something like this Class
class CreateArea extends React.Component {
// Some Code ....
}
Upvotes: 0
Views: 790
Reputation: 349
It would look like this:
import * as React from 'react';
export default class CreateArea extends React.Component {
constructor(props) {
super(props);
this.state = {
content: ''
};
}
onSubmit(e) {
e.preventDefault();
var date = moment().utcOffset('+05:30').format('hh:mm A DD-MM-YYYY');
firebase.firestore().collection('qna').add(
{
title: 'James',
this.state.content,
time: new Date(),
time2: date,
status: '0'
})
.then(() => {
this.setState({content: ''});
swal({
title: 'Question Submitted!',
text: 'Your Question is waiting for Approval.',
icon: 'success',
button: 'Close',
});
});
}
render(): React.ReactNode {
return (<div id="footer">
<form onSubmit={this.onSubmit.bind(this)}>
<textarea
name="content"
onChange={e => this.setState({content: e.currentTarget.value})}
value={this.state.content}
placeholder="Enter Your Question"
rows="2"
required
/>
<button></button>
</form>
</div>);
}
}
The most important details are to set the state in the constructor, add the render method and replace setContent
calls to setState
.
Upvotes: 0
Reputation: 3264
Replace
const [content, setContent] = useState('')
with
constructor(props) {
super(props);
this.state = {content: ''};
}
Replace
setContent('');
with
this.setState({content: ''})
and to access it, use this.state.content
Put your return function inside a render():
render() {
return (
<div id="footer">
....
);
}
Every function needs to be called with this now, for example:
<form onSubmit={this.onSubmit}>
Upvotes: 1
Reputation: 4469
Well, to convert your function component in a class component you have to initialize the state with this.state
and then declare a render function that will actually display the content, as in the following example:
class CreateArea extends React.Component {
constructor(props) {
super(props)
this.state = {
test: "test"
};
}
render() {
return (
<div>
content here
</div>
);
}
}
Upvotes: 0