how can i clean the input value after i click the button? - javascript

the below code works fine, but it has a small issue, it did not clean an input field value when I click the button, so I have tried to put a code this.setState({ name: ''}) into nameChangedHandler that make this input value back to empty, but it does not work and will lock the input value to empty, and then you could not type any data into this input value.
Does it work by using Component Lifecycle?
class AddPerson extends Component {
state = {
name: '',
age: '',
};
nameChangedHandler = event => {
this.setState({ name: event.target.value });
};
ageChangedHandler = event => {
this.setState({ age: event.target.value });
};
render() {
return (
<div className="AddPerson">
<input
type="text"
placeholder="Name"
onChange={this.nameChangedHandler}
value={this.state.name}
/>
<input
type="number"
placeholder="Age"
onChange={this.ageChangedHandler}
value={this.state.age}
/>
<button onClick={() => this.props.personAdded(this.state.name, this.state.age)}>
Add Person
</button>
</div>
);
}
}
export default AddPerson;

You clean the name in the button's onClick handler:
<button onClick={() => {
this.props.personAdded(this.state.name, this.state.age);
this.setState({ name: '' });
}}>
Add Person
</button>

class AddPerson extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
age: ""
};
}
nameChangedHandler = (event) => {
this.setState({ name: event.target.value });
};
ageChangedHandler = (event) => {
this.setState({ age: event.target.value });
};
handleSubmit = () => {
this.props.personAdded(this.state.name, this.state.age);
this.setState({
name: "",
age: ""
});
};
render() {
return (
<div className="AddPerson">
<input
type="text"
placeholder="Name"
onChange={this.nameChangedHandler}
value={this.state.name}
/>
<input
type="number"
placeholder="Age"
onChange={this.ageChangedHandler}
value={this.state.age}
/>
<button onClick={this.handleSubmit}>Add Person</button>
</div>
);
}
}
export default AddPerson;

Related

Toggle single element in React

I have one question. I created contact form in react and I want to collapsed only single contact, which was clicked. Toggle is method which should collapse it. And colapse is state. My problem is that when I click it affect all contact and all are collapsed. How can I improve it?
ContactBook.js
import React, { Component } from "react";
import Contact from "../Contact/Contact";
import "./ContactBook.css";
class ContactBook extends Component{
constructor(props){
super(props);
this.state = {
colapse :true,
contacts: [
{
id: 1,
name: 'Propulsion Academy',
address: 'Zurich',
avatar: 'propulsion-academy-logo.png'
},
{
id: 2,
name: 'Propulsion Academy',
address: 'Luzern',
avatar: 'propulsion-academy-logo.png'
},
{
id: 3,
name: 'Propulsion Academy',
address: 'Munich',
avatar: 'propulsion-academy-logo.png'
},
],
};
}
toggle=()=>{
const doesShow = this.state.colapse;
this.setState({colapse: !doesShow});
}
deleteContact=(contactIndex)=>{
//with slice method we create copy of an array
const contacts =this.state.contacts.slice();
contacts.splice(contactIndex, 1);
this.setState({contacts: contacts})
}
//get name from input
addName = e =>{
this.setState({
name: e.target.value,
})
}
//get address from input
addAddress = e =>{
this.setState({
address: e.target.value,
})
}
//update state on button click
handleSubmit = (e) =>{
e.preventDefault()
if(this.state.name && this.state.address) {
this.setState(state =>{
const newContact = {
id: Math.max(...state.contacts.map(c => c.id))+1,
name: this.state.name,
address: this.state.address,
}
return{
contacts:[...state.contacts, newContact]
}
})
}
}
render() {
return (
<div className="contactBook">
<form className ="addContact" >
<p>New Contact</p>
<label id="name"><p>Name</p><input type='text' id="name" onChange={this.addName}/></label>
<label id="address"><p>Address:</p><input type='text' id="address" onChange={this.addAddress} /></label>
<input type='file' name='file' />
<button type='submit' onClick= {this.handleSubmit}>SUBMIT</button>
</form>
<div className="contacts">
{this.state.contacts.map((contact, index) =>
< Contact key={contact.id} contact={contact} delete={()=>this.deleteContact(index)} colapse={this.state.colapse} toggle={this.toggle}/>)
}
</div>
</div>
);
}
};
export default ContactBook;
Contact.js
import React from "react";
import "./Contact.css";
import avatar from '../assets/user.png'
const Contact = (props) =>{
return (
<div className = "col" >
<img src={avatar} alt="avatar" onClick={props.toggle}/>
{props.colapse === true ?
<div>
<p>Name: {props.contact.name}</p>
<p>Address: {props.contact.address}</p>
<button onClick={props.delete}> Delete </button>
</div> : null
}
</div>
)
};
export default Contact;
I recommend to you to move the collapse and his method to the Contact component it self like this :
const Contact = (props) =>{
[collapse,setCollapse] = useState(true)
return (
<div className = "col" >
<img src={avatar} alt="avatar" onClick{()=>setCollape(prev=>!prev)}/>
{collapse === true ?
<div>
<p>Name: {props.contact.name}</p>
<p>Address: {props.contact.address}</p>
<button onClick={props.delete}> Delete </button>
</div> : null
}
</div>
)
};
In this component I created a state that will manage the collapse for each of the component the render in the map.
further more, the prev give you the last value you submit and it's best practice to use the prev instead of just setCollapse(!collapse)
You have one function for all contacts, and since you use .map() they will all behave the same, since toggling one toggles the state which is used to render all individual contacts. The solution would be to pass the selected contact in your state so your app actually knows which one is to be rendered! Hopefully that makes sense!
Good luck and let us know how things work out!
This is it:
ContactBook.js
import React, { Component } from "react";
import Contact from "./Contact";
// import "./ContactBook.css";
class ContactBook extends Component {
constructor(props) {
super(props);
this.state = {
contacts: [
{
id: 1,
name: "Propulsion Academy",
address: "Zurich",
avatar: "propulsion-academy-logo.png",
colapse: true
},
{
id: 2,
name: "Propulsion Academy",
address: "Luzern",
avatar: "propulsion-academy-logo.png",
colapse: true
},
{
id: 3,
name: "Propulsion Academy",
address: "Munich",
avatar: "propulsion-academy-logo.png",
colapse: true
}
]
};
}
// toggle = () => {
// const doesShow = this.state.colapse;
// this.setState({ colapse: !doesShow });
// };
deleteContact = contactIndex => {
//with slice method we create copy of an array
const contacts = this.state.contacts.slice();
contacts.splice(contactIndex, 1);
this.setState({ contacts: contacts });
};
togglecontact = contactIndex => {
let contacts = this.state.contacts.slice();
contacts[contactIndex].colapse = !contacts[contactIndex].colapse;
this.setState({ contacts: contacts });
};
//get name from input
addName = e => {
this.setState({
name: e.target.value
});
};
//get address from input
addAddress = e => {
this.setState({
address: e.target.value
});
};
//update state on button click
handleSubmit = e => {
e.preventDefault();
if (this.state.name && this.state.address) {
this.setState(state => {
const newContact = {
id: Math.max(...state.contacts.map(c => c.id)) + 1,
name: this.state.name,
address: this.state.address
};
return {
contacts: [...state.contacts, newContact]
};
});
}
};
render() {
return (
<div className="contactBook">
<form className="addContact">
<p>New Contact</p>
<label id="name">
<p>Name</p>
<input type="text" id="name" onChange={this.addName} />
</label>
<label id="address">
<p>Address:</p>
<input type="text" id="address" onChange={this.addAddress} />
</label>
<input type="file" name="file" />
<button type="submit" onClick={this.handleSubmit}>
SUBMIT
</button>
</form>
<div className="contacts">
{this.state.contacts.map((contact, index) => (
<Contact
key={contact.id}
contact={contact}
togglecontact={() => this.togglecontact(index)}
delete={() => this.deleteContact(index)}
colapse={this.state.colapse}
toggle={this.toggle}
/>
))}
</div>
</div>
);
}
}
export default ContactBook;
contactbook.js
import React from "react";
// import "./Contact.css";
const Contact = props => {
let buffer;
props.contact.colapse === true
? (buffer = (
<div>
<p>Name: {props.contact.name}</p>
<p>Address: {props.contact.address}</p>
<button onClick={props.delete}> Delete </button>
</div>
))
: null;
return (
<div className="col">
<img
onClick={props.togglecontact}
src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxASEhUQDxAVFhUQEhIVEBUQFhYVFhUSFhUXFxUSGBYYHSoiGBslGxYYIjEhJSkrLi4uFx8zODMtNygtLisBCgoKBQUFDgUFDisZExkrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIAOkA2AMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAABgcDBAUBAv/EAEMQAAIBAgMDCAYHBQgDAAAAAAECAAMRBBIhBQYxBxMiQVFhgaEycXKRscEjM0JSYpLRFHOisuEVFhc0Q1OC8FTC0v/EABQBAQAAAAAAAAAAAAAAAAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwC8YiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAifLuACSQAOJPASJ7Z34o07ph15xh9rgg8eLeHvgS6aOM2xhqWlWuinsLC/uGsq/GbcxmJOUu5v9ilcD3LqfGbGC3NxlTXmwgP+4beQuYE0q76YJf9Rm9lG+cwf37wfZU/L/Wcmhyev/qYlR3IhPmSPhM/+Hi/+S35B+sDrUt9cE3F2HtI3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zU71yUFjetm0DdYy63Os65npgcb+xnJqsz0i1VQOjRKpcNmDuoqXdx2hltNStuopRQHXMBXDM1PMPp2VnZFz9BgUGUktbXjJJEDknYoOIWuzLakcyBUIYuaZp5ncsQ3RY8FHVrpOsInsBERAREQP/Z"
/>
{buffer}
</div>
);
};
export default Contact;
can check it at:https://stackblitz.com/edit/react-mrvrr1?file=src%2FContact.js
only Toggling single element.

After button is clicked , Unable to reset the data

I entered some data in textbox and after that I clicked on the Button.
After clicked on the button The data should be reset.
class Header extends Component {
constructor(props) {
super(props)
this.state = {
title: 'React App',
keywords: 'Type Above'
}
}
inputData = (event) => {
console.log(event.target.value)
this.setState({ keywords: event.target.value ? event.target.value : 'Type Above' })
}
handleSubmit = (event) => {
event.preventDefault();
alert('Button Clicked');
this.setState({ keywords: "" });
}
render() {
return (
<div>
<h2>{this.state.title}</h2>
<form onSubmit ={this.handleSubmit}>
<center>
<input type="text"
placeholder="Search Value..."
onChange ={this.inputData} />
<h3>{this.state.keywords}</h3>
</center>
<button> BUtton </button>
</form>
</div>
)
}
}
Data should get reset after button is clicked...
You need to provide value prop to your input,
<input type="text"
placeholder="Search Value..."
onChange ={this.inputData}
value = {this.state.keywords}
/>
Lear more about Controlled Component.
Demo
class Header extends Component {
constructor(props) {
super(props);
this.state = {
title: "React App",
keywords: "Type Above"
};
}
inputData = event => {
console.log(event.target.value);
this.setState({
keywords: event.target.value ? event.target.value : "Type Above"
});
};
handleSubmit = event => {
event.preventDefault();
alert("Button Clicked");
this.setState({ keywords: "" });
};
render() {
return (
<div>
<h2>{this.state.title}</h2>
<form onSubmit={this.handleSubmit}>
<center>
<input
type="text"
placeholder="Search Value..."
value={this.state.keywords === 'Type Above' ? '' : this.state.keywords}
onChange={this.inputData}
/>
<h3>{this.state.keywords}</h3>
</center>
<button> BUtton </button>
</form>
</div>
);
}
}
your problem is that you didn't assign the keywords value to the input, because the value is correctly deleted after you click the button, you can see it here:
class Header extends Component {
state = {
title : 'React App',
keywords : 'Type Above'
};
inputData = event => {
console.log(event.target.value)
this.setState({ keywords: event.target.value ? event.target.value : 'Type Above' });
};
handleSubmit = event => {
event.preventDefault();
alert('Button Clicked');
this.setState({ keywords: "" });
};
render() {
const { keywords, title } = this.state;
return (
<div>
<h2>{title}</h2>
<form onSubmit={this.handleSubmit}>
<center>
<input
type="text"
placeholder="Search Value..."
onChange={this.inputData}
value={keywords}
/>
<h3>{keywords}</h3>
</center>
<button>Button </button>
</form>
</div>
)
}
}
Hope this helps, Regards.
You are missing value attribute for your input. You need to add something like this value={this.state.keywords}

How to dynamically add fields to a form on React

I make a simple react app.
I have a React form with field.
And we can add dynamically more and more same fields. And submit them together.
Maybe I can use for or while? But how?
And I must add dynamically fields name in form, and dynamically fields to object for submit.
class Form extends Component {
constructor(props) {
super(props);
this.state = {
task: '',
count: [1]
};
this.addTask = this.addTask.bind(this);
this.change = this.change.bind(this);
}
render() {
return (
<div>
<h1>Form</h1>
<form onSubmit = {this.onSubmit} method='post'>
<div>
{this.state.count.map((item, index) => {
return (
<div key={index}>
<input type='text' value={this.state.task} name='task' onChange={this.change} />
</div>
)
})}
</div>
<button onClick={this.addTask}>addTask</button>
<button>submit</button>
</form>
</div>
);
}
addTask(e) {
e.preventDefault();
this.setState({
count: [...this.state.count, '1']
})
}
onSubmit = (e) => {
e.preventDefault();
const {submit} = this.props;
submit({
task: this.state.task
});
this.setState({
task: ''
})
};
change(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
}
export default connect(null, { submit })(Form);
You can map through an array of your objects:
constructor(props) {
super(props);
this.state = {
task: '',
count: [1],
components: []
};
this.addTask = this.addTask.bind(this);
this.change = this.change.bind(this);
}
render() {
return (
<div>
<h1>Form</h1>
<form onSubmit = {this.onSubmit} method='post'>
<div>
{this.state.count.map((item, index) => {
return (
<div key={index}>
{this.state.components.map(comp => comp)}
</div>
)
})}
</div>
<button onClick={this.addTask}>addTask</button>
<button>submit</button>
</form>
</div>
);
}
addTask(e) {
e.preventDefault();
this.setState({
count: [...this.state.count, '1'],
components: this.state.components.concat(<input type='text' value={this.state.task} name='task' onChange={this.change} key={this.state.count.length + 1} />)
})
}

Axios Post Form with Reactjs

So I have this post method with Axios and if I submit this, it said
Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
If I use this method:
axios.post('http://localhost:5000/users', ({userid: this.state.userid})
it works. But if I add 2 or more arg to the axios post it gets error again:
axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))
Here is my full code. As you can see I try different combinations of code, and it only works if I only pass 1 arg.
import React from 'react';
import axios from 'axios';
// import { Form } from 'antd';
// import { List, Card, Form } from 'antd';
export default class FormUser extends React.Component {
// constructor(props) {
// super(props)
// this.state = {
state = {
userid: '',
fullname: '',
usergroup:'',
emailid: '',
mobile: '',
title: '',
};
handleChange = event => {
this.setState({ userid: event.target.value });
this.setState({ fullname: event.target.value });
this.setState({ usergroup: event.target.value });
this.setState({ emailid: event.target.value });
this.setState({ mobile: event.target.value });
this.setState({ title: event.target.value });
}
handleSubmit = event => {
event.preventDefault();
// const userform = {userid: this.state.userid};
// const fullnameForm = {fullname: this.state.fullname};
// const usergroupForm = {usergroup: this.state.usergroup};
// const emailidForm = {emailid: this.state.emailid};
// const mobileForm = {mobile: this.state.mobile};
// const titleForm = {title: this.state.title};
axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))
// { {userid: this.state.userid}, {fullname: this.state.fullname} , usergroup: this.state.usergroup, emailid: this.state.emailid, mobile: this.state.mobile, title: this.state.title })
// { userform, fullnameForm, usergroupForm, emailidForm, mobileForm, titleForm })
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>User Project ID: <input type="text" name="userid" onChange={this.handleChange}/></label><br/>
<label>Full Name: <input type="text" name="fullname" onChange={this.handleChange}/></label><br/>
<label>User Group: <input type="text" name="usergroup" onChange={this.handleChange}/></label><br/>
<label>Email: <input type="text" name="emailid" onChange={this.handleChange}/></label><br/>
<label>Mobile: <input type="text" name="mobile" onChange={this.handleChange}/></label><br/>
<label>Title: <input type="text" name="title" onChange={this.handleChange}/></label>
<button type="submit">Add</button>
</form>
)
}
}
AXIOS POST on Express
app.post('/users', function (req, res) {
var postData = req.body;
// postData.created_at = new Date();
connection.query("INSERT INTO users SET ?", postData, function (error, results, fields) {
if (error) throw error;
console.log(results.insertId);
res.end(JSON.stringify(results));
});
});
eventHandler for each state. Is there any way I can do this better?
yes it would work something like this
import React, { Component } from 'react';
class UserForm extends Component {
constructor() {
super();
this.state = {
fname: '',
lname: '',
email: '',
};
}
onChange = (e) => {
/*
Because we named the inputs to match their
corresponding values in state, it's
super easy to update the state
*/
this.setState({ [e.target.name]: e.target.value });
}
render() {
const { fname, lname, email } = this.state;
return (
<form>
<input
type="text"
name="fname"
value={fname}
onChange={this.onChange}
/>
<input
type="text"
name="lname"
value={lname}
onChange={this.onChange}
/>
<input
type="text"
name="email"
value={email}
onChange={this.onChange}
/>
</form>
);
}
}
and about submission of the form your axios post would work something like this
onSubmit = (e) => {
e.preventDefault();
// get our form data out of state
const { fname, lname, email } = this.state;
axios.post('/', { fname, lname, email })
.then((result) => {
//access the results here....
});
}
axios.post(url[, data[, config]])'s 3rd argument is the Axios configuration object, which you're inadvertently passing in in
axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))
so the request gets misconfigured and doesn't work.
Instead, all of the data to POST should be in the single data object.
axios.post('http://localhost:5000/users', {
userid: this.state.userid,
fullname: this.state.fullname,
})
So apparently I have to add eventhandler for each state. Is there any way I can do this better?
import React from 'react';
import axios from 'axios';
import { Form } from 'antd';
// import { List, Card, Form } from 'antd';
const FormItem = Form.Item;
export default class FormUser extends React.Component {
// constructor(props) {
// super(props)
// this.state = {
state = {
userid: '',
fullname: '',
usergroup: '',
emailid: '',
mobile: '',
title: '',
};
handleUserIDChange = event => {this.setState({ userid: event.target.value })}
handleFullNameChange = event => {this.setState({ fullname: event.target.value })}
handleUserGroupChange = event => {this.setState({ usergroup: event.target.value })}
handleEmailIDChange = event => {this.setState({ emailid: event.target.value })}
handleMobileChange = event => {this.setState({ mobile: event.target.value })}
handleTitleChange = event => {this.setState({ title: event.target.value })}
handleSubmit = event => {
event.preventDefault();
// const userform = {userid: this.state.userid};
// const fullnameForm = {fullname: this.state.fullname};
// const usergroupForm = {usergroup: this.state.usergroup};
// const emailidForm = {emailid: this.state.emailid};
// const mobileForm = {mobile: this.state.mobile};
// const titleForm = {title: this.state.title};
axios.post('http://localhost:5000/users',
{ userid: this.state.userid, fullname: this.state.fullname, usergroup: this.state.usergroup, emailid: this.state.emailid, mobile: this.state.mobile, title: this.state.title },)
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
// const formItemLayout = {
// labelCol: {
// xs: { span: 24 },
// sm: { span: 8 },
// },
// wrapperCol: {
// xs: { span: 24 },
// sm: { span: 16},
// },
// };
<Form onSubmit={this.handleSubmit}>
<FormItem>
<label>User Project ID: <input type="text" name="this.state.userid" onChange={this.handleUserIDChange} /></label>
</FormItem>
<FormItem>
<label>Full Name: <input type="text" name="this.state.fullname" onChange={this.handleFullNameChange} /></label><br />
</FormItem>
<FormItem>
<label>User Group: <input type="text" name="this.state.usergroup" onChange={this.handleUserGroupChange} /></label><br />
</FormItem>
<FormItem>
<label>Email: <input type="text" name="this.state.emailid" onChange={this.handleEmailIDChange} /></label>
</FormItem>
<FormItem>
<label>Mobile: <input type="text" name="this.state.mobile" onChange={this.handleMobileChange} /></label>
</FormItem>
<FormItem>
<label>Title: <input type="text" name="this.state.title" onChange={this.handleTitleChange} /></label>
</FormItem>
<button type="submit">Add</button>
</Form>
)
}
}

enable button to submit only when all the fields are filled

I have a form which has 3 field. First two fields are email_from and email_subject and the last field is an editor. I have used draftjs for editor. If there is no editor i could enable and disable the submit button but due to the inclusion of the editor i did not know how can i enable the button only when all the fields are filled with no error.
Here is my code.
AdminEditor is the component which has draftjs editor
class EmailTemplate extends React.Component {
state = {
emailSubject: '',
emailFrom: ''
};
handleChange = event =>
this.setState({ [event.target.name]: event.target.value });
handleSubmit = event => {
event.preventDefault();
};
render() {
const { emailSubject, emailFrom } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<FieldGroup
id="formControlsText"
name="emailSubject"
type="text"
label="Email Subject"
placeholder="Enter Email Form"
onChange={this.handleChange}
validationState={emailSubject ? 'success' : 'error'}
required
/>
<FieldGroup
id="formControlsText"
name="emailFrom"
type="email"
label="Email From"
placeholder="Enter Email From"
onChange={this.handleChange}
validationState={emailFrom ? 'success' : 'error'}
required
/>
<AdminEditor />
<Button type="submit">
Submit
</Button>
</form>
);
}
}
export default EmailTemplate;
class AdminEditor extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
isEmpty: true
};
}
onEditorStateChange = editorState => {
this.setState({
editorState
});
};
onEditorChange = editorContent => {
this.setState({
editorContent
});
};
handleChange = event =>
this.state.editorState.getCurrentContent().hasText()
? this.setState({ isEmpty: false })
: this.setState({ isEmpty: true });
render() {
const { editorState } = this.state;
return (
<div>
<Editor
editorState={this.state.editorState}
initialContentState={rawContentState}
toolbarClassName="home-toolbar"
wrapperClassName="home-wrapper"
editorClassName="home-editor"
onEditorStateChange={this.onEditorStateChange}
toolbar={{
textAlign: { inDropdown: true },
}}
onContentStateChange={this.onEditorChange}
placeholder="write text here..."
onChange={this.handleChange}
/>
</div>
);
}
}
export default AdminEditor;
Can anyone please help me?
There are many ways to do this, mostly based around passing some callbacks down into the controlled component which updates the state in the parent.
A simple way would be to pass a handler that sets a flag if the editor is empty or not:
class AdminEditor extends React.PureComponent {
...
handleChange = event =>
this.props.setEditorIsEmpty(
this.state.editorState.getCurrentContent().hasText()
);
Then in EmailTemplate:
setEditorIsEmpty(editorIsEmpty) {
this.setState({
editorIsEmpty
});
}
render() {
const { emailSubject, emailFrom } = this.state;
return (
<form onSubmit={this.handleSubmit}>
...
<AdminEditor
setEditorIsEmpty={this.setEditorIsEmpty}
/>
<Button
type="submit"
disabled={!emailSubject || !emailFrom || editorIsEmpty}>
Submit
</Button>
</form>
);
}

Categories

Resources