Custom React component(react-hook) not re-rendering - javascript

I have a component that fetches data from my mongoDB it then renders a list of child components. It the "list" component I have a post that adds a new member to the database. Upon addition im trying to get the list to re-fetch the data and re-render the list component.
List Component:
import React, { useState, useEffect } from "react";
import axios from "axios";
import Spinner from "react-bootstrap/Spinner";
import { toast } from "react-toastify";
import DatePicker from "react-datepicker";
import useForm from "react-hook-form";
import { css } from "glamor";
import "react-toastify/dist/ReactToastify.css";
import "react-datepicker/dist/react-datepicker.css";
import "../Styles/ReactDatePicker.css";
import Member from "./Member";
const { getFamily, getMembers, postMember } = require("../Utils/Service");
const MemberList = () => {
const [family, setFamily] = useState({});
const [familyMembers, setFamilyMembers] = useState([]);
const [loading, setLoading] = useState(true);
const [date, setDate] = useState(new Date());
const { handleSubmit, register, errors } = useForm();
async function fetchData() {
getFamily.then(result => {
setFamily(result);
});
getMembers.then(result => {
try {
setFamilyMembers(
result.map((child, index) => (
<Member
key={index}
index={child._id}
balance={child.balance}
firstName={child.firstName}
lastName={child.lastName}
birthday={child.birthday}
role={child.role[0]}
/>
))
);
} catch (e) {
toast.error("500: Error with Service Call", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
className: css({
background: "#ed5565 !important"
})
});
} finally {
setLoading(false);
}
});
}
useEffect(() => {
if (loading) {
fetchData();
}
}, [loading]);
// const handleDateChange = date => {
// setDate(date)
// }
const onSubmit = data => {
data.familyId = "5dddf14df965552b3da57be1";
postMember(data).then(
????????????
);
};
return (
<div className="ibox">
<div className="ibox-title">
<h5>{family.name}</h5>
<div className="ibox-tools">
<span className="label label-warning-light float-right">
{familyMembers.length} Member(s)
</span>
</div>
</div>
<div className="ibox-content">
<div className="feed-activity-list">
{loading ? (
<Spinner animation="grow" role="status" variant="dark">
<span className="sr-only">Loading...</span>
</Spinner>
) : (
familyMembers
)}
</div>
<div className="d-flex">
<a
className="btn btn-primary text-white m-t"
data-toggle="modal"
data-target={"#newMemberModel"}
>
<i className="fa fa-plus"></i> New Member
</a>
<a
className="btn btn-danger text-white m-t m-l"
data-toggle="modal"
data-target={"#removeMemberModel"}
>
<i className="fa fa-minus"></i> Remove Member
</a>
</div>
</div>
{/* New Member Model */}
<div
className="modal inmodal"
id={"newMemberModel"}
tabIndex="-1"
role="dialog"
style={{ display: "none" }}
aria-hidden="true"
>
<div className="modal-dialog">
<div className="modal-content animated fadeIn">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span className="sr-only">Close</span>
</button>
<h4 className="modal-title">New Family Member</h4>
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="modal-body">
<div className="row">
<div className="col">
<div className="form-group">
<label>First Name</label>
<input
type="text"
placeholder="First Name"
className="form-control"
name="firstName"
ref={register({
required: true,
pattern: {
value: /^[a-zA-Z]+$/i,
message: "Invalid First Name"
}
})}
/>
<div className="text-danger">
{errors.firstName && errors.firstName.message}
</div>
</div>
<div className="form-group">
<label className="font-normal">Birthday</label>
<div className="input-group date">
{/* <DatePicker
selected={date}
onChange={handleDateChange}
placeholderText="Click to select a date"
isClearable
peekNextMonth
showMonthDropdown
showYearDropdown
dropdownMode="select"
ref={e =>register({
name: "Birthday",
required: false
})}
/> */}
<input
type="text"
placeholder="01/01/01"
className="form-control"
name="birthDate"
ref={register({
required: false
})}
/>
</div>
</div>
</div>
<div className="col">
<div className="form-group">
<label>Last Name</label>
<input
type="text"
placeholder="Last Name"
className="form-control"
name="lastName"
ref={register({
required: true,
pattern: {
value: /^[a-zA-Z]+$/i,
message: "Invalid Last Name"
}
})}
/>
<div className="text-danger">
{errors.lastName && errors.lastName.message}
</div>
</div>
<div className="form-group">
<label>Role</label>
<select
className="custom-select"
name="role"
ref={register({ required: true })}
>
<option defaultValue>Select Role</option>
<option value="Adult">Adult</option>
<option value="Child">Child</option>
</select>
</div>
</div>
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-white"
data-dismiss="modal"
>
Close
</button>
<button type="submit" className="btn btn-primary">
Add Member
</button>
</div>
</form>
</div>
</div>
</div>
{/* Remove Member Model */}
<div
className="modal inmodal"
id={"removeMemberModel"}
tabIndex="-1"
role="dialog"
style={{ display: "none" }}
aria-hidden="true"
>
<div className="modal-dialog">
<div className="modal-content animated fadeIn">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span className="sr-only">Close</span>
</button>
<h4 className="modal-title">Remove Family Member</h4>
</div>
<div className="modal-body"></div>
<div className="modal-footer">
<button
type="button"
className="btn btn-white"
data-dismiss="modal"
>
Close
</button>
<button type="button" className="btn btn-danger">
Remove Member
</button>
</div>
</div>
</div>
</div>
</div>
);
};
export default MemberList;
within the code in the onSubmit function with posts the data inside the .then is where im trying to re-render the entire component and/or fetch the data agin.

right now, your useEffect is only dependent on the property loading, if you change the property then the effect will run again.
https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect

In your component, you can call this.forceUpdate() to force a rerender.
I think you can also call your fetchData function again inside your .then() block, if you make the callback inside the .then() an async function.
postMember(data).then(
async () => this.fetchData()
);
or
postMember(data).then(
() => this.forceUpdate()
);

Related

How to pass value of inputs to other function?

I create multiple step button with useState hook and it work fine. Now I trying pass value of inputs from step two of button to step three. There is a problem I can't pass props or state in my function and I have error that state or props is undefined. I try more and more but give nothing.
This is my code :
const ShowOrNot = () => {
const [showForm, setShowForm] = useState(false);
const [showPreview, setShowPreview] = useState(false);
const [formHidden, setFormHidden] = useState(false);
return (
<div className="col-12">
{!showForm ? (
<ShowFormButton onClick={() => setShowForm(true)}/>
) : undefined}
{showForm ? (
<div className={''} id="scrollbar-style">
<div>
<HideFormButton
onClick={() => {
setShowForm(false);
}}
/>
</div>
{!formHidden ? <MyForm/> : undefined}
{!showPreview ? (
<ShowPreviewButton
onClick={() => {
setShowPreview(true);
setFormHidden(true);
}}
/>
) : undefined}
{showPreview ? (
<div className={"preview-send-wrapper"}>
<div className={"preview-send-header"}>
<div className={"preview-send-header-icon"}>
</div>
<h2>
Preview
</h2>
</div>
<div className={"mt-5 preview-send-cover"}>
<img src={value of inputs} alt={"cover"}/>
</div>
<div className={" preview-send-video-poster"}>
<img src={value of inputs} alt={"cover"}/>
<h1 className={"mt-4"}>
{this.props.videoTitle} // one value of inputs get here
<span>{two value of inputs get here}</span>
</h1>
<h4 className={"mt-3"}>
{value of inputs}
</h4>
</div>
<div className={"preview-send-summary-video"}>
<p>
{value of inputs}
</p>
</div>
<Row>
<div className={"col-lg-8 col-12"}>
<button className={"send-video-btn-final"}>
Send
</button>
</div>
<div className={"col-lg-4 col-12"}>
<SendButton
onClick={() => {
setFormHidden(false);
setShowPreview(false);
setShowForm(true);
}}
/>
</div>
</Row>
</div>
) : undefined}
</div>
) : undefined}
</div>
);
};
function SendButton({onClick}) {
return (
<div>
<button className="edit-send-video-btn w-100" onClick={onClick}>
Edit
</button>
</div>
);
}
function ShowFormButton({onClick}) {
return (
<div>
<button className="upload-content-btn w-100" onClick={onClick}>
<span className="ml-2">
</span>new upload{' '}
</button>
</div>
);
}
function ShowPreviewButton({onClick}) {
return (
<div className={"row show-preview-button"}>
<div className="col-lg-8 col mt-3">
<button className="preview-send-data-btn" onClick={onClick}>
Preview
</button>
</div>
<div className="col-lg-4 col mt-3">
<button className="draft-send-data-btn">Draft</button>
</div>
</div>
);
}
function HideFormButton({onClick}) {
return (
<div className={'content-send-form-close-btn'}>
<button onClick={onClick} className={'close-modal-btn'}>
<span>Close</span>
</button>
</div>
);
}
class MyForm extends Component {
constructor(props) {
super(props);
this.state = {
videoTitle: "",
category: "",
summary: "",
videoText: "",
}
}
onChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
render() {
return (
<div className={"content-send-form-wrapper"}>
<div className={'content-send-form-header'}>
<div className={'content-send-form-header-title'}>
</div>
</div>
<form className={'mt-3 content-send-form-data register-teacher-inputs-box '}>
<Row>
<div className={'col-lg-6 col-12 mt-4'}>
<label htmlFor={'name'} className={' text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'Title'}
name={'videoTitle'}
required="true"
value={this.state.videoTitle}
onChange={this.onChange}
onBlur={(e) => (e.target.placeholder = 'Title')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
<div className={'col-lg-6 col-12 mt-4'}>
<label htmlFor={'country'} className={' text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'category'}
name={'category'}
value={this.state.category}
onChange={this.onChange}
required="true"
onBlur={(e) => (e.target.placeholder = 'category')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3 video-upload-input-btn">
<VideoUpload/>
</div>
</Row>
<Row>
<div className="col-lg-6 col-12 mt-3">
<PosterUpload/>
</div>
<div className="col-lg-6 col-12 mt-3">
<CoverUpload/>
</div>
</Row>
</form>
</div>
);
}
}

React needs to be handled some if conditions

I have an issue with the if statement. The problem is I need to create a condition if the array has 2 object needs to be true if has 1 object it should be false. the objects are strings please check the code.
const { program } = useContext(ProgramContext);
const { authMethods } = program;
let loginComponent;
let claimComponent;
let insertRow;
let insertEnd;
if (authMethods) {
if (authMethods.indexOf('login') !== -1) {
loginComponent = (
<div className="col-md-6 d-flex">
<div className="card flex-grow-1 mb-md-0">
<div className="card-body">
<h3 className="card-title">Login</h3>
<form>
<div className="form-group">
<label htmlFor="login-id">User ID</label>
<input
id="login-id"
className="form-control"
placeholder="Please enter user ID"
/>
</div>
<div className="form-group">
<label htmlFor="login-password">Password</label>
<input
id="login-password"
type="password"
className="form-control"
placeholder="Password"
/>
<small className="form-text text-muted">
<ErrModal />
</small>
</div>
<div className="form-group">
<div className="form-check">
<span className="form-check-input input-check">
<span className="input-check__body">
<input
id="login-remember"
type="checkbox"
className="input-check__input"
/>
<span className="input-check__box" />
<Check9x7Svg className="input-check__icon" />
</span>
</span>
<label className="form-check-label" htmlFor="login-remember">
Remember Me
</label>
</div>
</div>
<button type="submit" className="btn btn-primary mt-2 mt-md-3 mt-lg-4">
Login
</button>
</form>
</div>
</div>
</div>
);
}
if (authMethods.indexOf('claim') !== -1) {
claimComponent = (
<div className="col-md-6 d-flex mt-4 mt-md-0">
<div className="card flex-grow-1 mb-0">
<div className="card-body">
<h3 className="card-title">Claim</h3>
<form>
<div className="form-group">
<label htmlFor="claim-code">Enter Claim Code</label>
<input
id="register-email"
type="text"
className="form-control"
placeholder="Claim Code"
/>
</div>
<button type="submit" className="btn btn-primary" style={{ marginTop: '186px' }}>
Claim
</button>
</form>
</div>
</div>
</div>
);
}
}
console.log(loginComponent);
console.log(claimComponent);
const rowComponent = (
<div className="container">
{insertRow}
{loginComponent}
{claimComponent}
{insertEnd}
</div>
);
Basically I want to add row class if there are 2 items in the array otherwise I don't need a row.
thank you
Your question is not clear so I'll chalk out a similar example:
import React from 'react'
const Component = () => {
const arr = ["foo", "bar"];
const rowClass = arr.length === 2 ? "row" : "";
return (
<div className={rowClass}>
This is an example
</div>
)
}
export default Component

How can i pass the data inside setState to modal REACTJS

How can i pass my tabledata to my modal, im doing edit function
<button className="btn btn-info btn-icon btn-circle btn-md m-r-2 float-right" onClick={() =>
this.toggleModal("modalWithoutAnimation", tabledata)
);}}><i className="fa fa-edit"></i>
</button>
heres my modal, i added the this.state.modalWithoutAnimation
{this.state.modalWithoutAnimation && <Modal isOpen={this.state.modalWithoutAnimation} fade={false} toggle={() => this.toggleModal("modalWithoutAnimation")}>
<ModalHeader toggle={() => this.toggleModal("modalWithoutAnimation")}>
Edit Department
</ModalHeader>
<form className="margin-bottom-0" onSubmit={this.handleEdit}>
<ModalBody>
<h3><label className="control-label">Module Information </label></h3>
<div className="row row-space-10">
<div className="col-md-4 m-b-15">
<label className="control-label">Module Name <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Module Name" name="moduleName" value={this.state.moduleName} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Course <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Course" name="courseId" defaultValue={localcourseid} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Sequence Number <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Sequence Number" name="sequenceNo" value={this.state.sequenceNo} onChange={this.handleChange} required="" />
</div>
</div>
</ModalBody>
<ModalFooter>
<button onClick={(e) => {
this.handleEdit(e, this.state.id)
console.log(this.state.id)
this.addNotification('success', 'Success', 'All data has been successfully saved', 'bottom-right')
this.toggleModal("modalWithoutAnimation")
}} className="btn btn-sm btn-success">Save Edit</button>
<button
className="btn btn-white btn-sm"
onClick={() => this.toggleModal("modalWithoutAnimation")} >
Close
</button>
</ModalFooter>
</form>
</Modal>
}
here's the state together with the function togglemodal cant seem to display the this.state.moduleName etc. Im totally lost but in my console log i can display state of the clicked data
this.state = {
error: null,
isLoaded: false,
modalDialog: false,
modalWithoutAnimation: false,
modalMessage: false,
modalAlert: false,
id:'',
moduleName:'',
courseId:'',
sequenceNo:'',
}
//binded elements
this.toggleCollapse = this.toggleCollapse.bind(this);
this.toggleModal = this.toggleModal.bind(this);
this.toggleSweetAlert = this.toggleSweetAlert.bind(this);
this.addNotification = this.addNotification.bind(this);
this.notificationDOMRef = React.createRef();
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.handleEditChange = this.handleEditChange.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.handletoggleClose = this.handletoggleClose.bind(this);
}
//event for toggling modal
toggleModal(name, tabledatas) {
switch (name) {
case 'modalDialog':
this.setState({ modalDialog: !this.state.modalDialog });
break;
case 'modalWithoutAnimation':
this.setState({ modalWithoutAnimation: !this.state.modalWithoutAnimation,
state:tabledatas
});
break;
case 'modalMessage':
this.setState({ modalMessage: !this.state.modalMessage });
break;
case 'modalAlert':
this.setState({ modalAlert: !this.state.modalAlert });
break;
default:
break;
}
}
Enable model popup only on click, save data to state and pass to model popup like this-
<button className="btn btn-info btn-icon btn-circle btn-md m-r-2 float-right"
onClick={()=>this.handleToggle(tabledata)}><i className="fa fa-edit"></i>
</button>
function handleToggle
handleToggle=data=>{
this.setState({state:data, toggle:true })
}
jsx
{this.state.toggle && <Modal>
<h3><label className="control-label">Module Information </label></h3>
<div className="row row-space-10">
<div className="col-md-4 m-b-15">
<label className="control-label">Module Name <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Module Name" name="moduleName" value={this.state.moduleName} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Course <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Course" name="courseId" defaultValue={localcourseid} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Sequence Number <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Sequence Number" name="sequenceNo" value={this.state.sequenceNo} onChange={this.handleChange} required="" />
</div>
</div>
</ModalBody>
<ModalFooter>
<button onClick={(e) => {
this.handleEdit(e, this.state.id)
console.log(this.state.id)
this.addNotification('success', 'Success', 'All data has been successfully saved', 'bottom-right')
this.toggleModal("modalWithoutAnimation")
}} className="btn btn-sm btn-success">Save Edit</button>
<button
className="btn btn-white btn-sm"
onClick={() => this.toggleModal("modalWithoutAnimation")} >
Close
</button>
</ModalFooter>
</form>
</Modal>}

Update value in Firebase and React

I have added a menu in my database in firebase and now I want to edit the menu in the database. But whenever I send a request to update the menu it only updates the first menu. No matter which menu I choose, it always updates the first menu in the database.
This is my part of an editMenu component which has a button that links to EditmenuForm.
`
contentMenuKeys.map(t=>{
// if (t === this.state.Appetizer)`
return(
<div className="text-center">
<h4>{t}</h4>
<div className="row">
{Object.keys(this.props.menu[t]).map(menu=>{
return(
[this.props.menu[t][menu]].map(item=>{
return(
<div className="col-md-6 menuItems" >
<div className="textM d-flex">
<div className="one-half">
<h3>{item.Name}</h3>
<p><span>{item.Description}</span></p>
</div>
<div className="one-forth">
<span className="price">${item.Price}</span>
<p><span>
<button type="button" className="btn btn-primary" data-toggle="modal" data-target="#MenuEditModal">Edit</button ><MenuEditForm Menu_Type={t} Name={item.Name}Description={item.Description} Price={item.Price}iID={menu} rID={queryString.parse(this.props.location.search).id }/>{" "}
<button type="submit" onClick={()=>{this.props.deleteMenu({rID:queryString.parse(this.props.location.search).id,Menu_Type:t,iID:menu})}} className="btn btn-danger ml-2">Remove</button>
</span></p>
</div>
</div>
</div>
)
})
)
})
}`
And below is MenuEditForm component which has edit menu form.
`import React,{Component} from 'react'
import {connect} from "react-redux"
import propTypes from "prop-types"
import { editMenu } from "../../actions/addMenu"
export class MenuEditForm extends Component {
state={
Name:"",
Description: "",
Price:"",
Menu_Type:"",
rID:""
}static propTypes={
editMenu: propTypes.func.isRequired
}`
onChange=e=> this.setState({[e.target.name]:e.target.value});
onSubmit=e=>{
console.log("reached");
e.preventDefault();
const { Name, Description, Price, rID, Menu_Type } = this.state;
const menu = { Name, Description, Price, Menu_Type, rID, iID:this.props.iID };
this.props.editMenu(menu);
this.setState({
Name:"",
Description: "",
Price:"",
Menu_Type:"",
});
}
componentDidMount(){
this.setState({rID:this.props.rID})
}
render(){const {Name, Description, Price, Menu_Type}=this.state;
return(
<div>
<form onSubmit={this.onSubmit}>
<div className="modal fade" id="MenuEditModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel">Edit Items</h5>
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<div>
<div className="modal-body">
<div className="ml-4 mr-4 mt-4 mb-4">
<div className="form-group">
<label>Menu_Type</label>
<select name="Item Type" id="Item-Type" value={Menu_Type} onChange={this.onChange} name="Menu_Type">
<option value="None">None</option>
<option value="Appetizers">Appetizers</option>
<option value="Entrees">Entrees</option>
</select>
</div>
<div className="form-group">
<label>Name</label>
<input
className="form-control"
type="text"
name="Name"
onChange={this.onChange}
value={Name}
required
/>
</div>
<div className="form-group">
<label>Description</label>
<input
className="form-control"
type="text"
name="Description"
onChange={this.onChange}
value={Description}
required
/>
</div>
<div className="form-group">
<label>Price</label>
<input
className="form-control"
type="text"
name="Price"
onChange={this.onChange}
value={Price}
required
/>
</div>
</div>
<div className="modal-footer">
<button type="button" id="cancel" className="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" className="btn btn-primary" >Change Items</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
)
}}export default connect(null,{editMenu})(MenuEditForm)
This is my editMenu action
export const editMenu =(item) =>(dispatch)=>{
axios
.post("/api/database/editMenu", item)
.then(res => {
dispatch({
type:EDIT_MENU,
payload:res.data
});
})
.catch(err=>
dispatch(returnErrors(err.response.date,err.response.status)));
My editMenuAPI
class editMenuAPI(generics.GenericAPIView):
permission_classes=[
permissions.AllowAny
]
def post(self, request):
try:
print(request.data)
db = firebase.editMenu(request.data)
return Response({
"status": "success"
})
except:
return Response({
"status":"Disconnected",
"msg": 'There was a problem'
})
This is editMenu function in firebase.
def editMenu(request):
db=credentials().database()
mType = request['Menu_Type']
rID=request['rID']
iID =request['iID']
print(request)
request.pop("Menu_Type")
request.pop('rID')
request.pop('iID')
return db.child('Restaurants').child(rID).child("Menu").child(mType).child(iID).update(request)

email real time component in react

I'm trying to create a mailbox component in order to get the real-time data displayed in my mailbox component I use trumbowyg for creating the WYSIWYG editor and bootstrap but I can't manage to get it real-time
<script type="text/babel">
var Modal = React.createClass({
render: function () {
return (
<div className="modal fade" tabIndex="-1" role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" ><span>×</span></button>
<h4 className="modal-title">{this.props.title}</h4>
</div>
<div className="modal-body">
{this.props.body}
</div>
<div className="modal-footer">
<div className="btn-toolbar pull-right" role="toolbar">
<div className="btn-group" role="group">
<button type="button" className="btn btn-danger outline" data-dismiss="modal">Close</button>
</div>
</div>
<div className="clearfix" />
</div>
</div>
</div>
</div>
);s
}
});
var Editor = React.createClass({
getDefaultProps: function () {
return {
body: "",
placeholder: "Enter your message here..."
};
},
componentWillReceiveProps: function (nextProps) {
if (nextProps.body == ""){
$('#editor').trumbowyg('empty');
}
},
componentDidMount: function () {
var that = this;
$('#editor').trumbowyg({
fullscreenable: false
})
.on('tbwchange', function (){
that.props.onChange($('#editor').trumbowyg('html'));
});
$('#editor').trumbowyg('html', this.props.body);
},
render: function () {
return <div id="editor" placeholder={this.props.placeholder} ></div>;
}
});
var Mailbox = React.createClass({
getInitialState: function () {
return {
"emailTo": "",
"emailCC": "",
"emailBCC": "",
"emailSubject": "",
"emailBody": ""
}
},
render: function () {
return (
<div className="panel panel-default">
<div className="panel-heading">
<div className="row">
<div className="col-xs-8 center">
<div className="inbox-title">
<span className="glyphicon glyphicon-envelope center"></span>
<h2 className="center">{this.props.title}</h2>
</div>
</div>
<div className="col-xs-4 center">
<div className="inbox-avatar text-right">
<img src={this.props.urlImage} />
<div className="inbox-avatar-name"><a href={this.props.link}>{this.props.username}</a></div>
</div>
</div>
</div>
<hr />
<div className="row">
<div className="col-xs-12">
<form className="form-horizontal">
<div className="form-group">
<label htmlFor="email-to" className="col-sm-1 control-label">To</label>
<div className="col-sm-11">
<input type="email"
className="form-control"
id="email-to"
value={this.state.emailTo}
placeholder="Ex: hello#example.com"
onChange={this.handleEmailToChange}/>
</div>
</div>
<div className="form-group">
<label htmlFor="email-cc" className="col-sm-1 control-label">CC</label>
<div className="col-sm-11">
<input type="email"
className="form-control"
id="email-cc"
value={this.state.emailCC}
onChange={this.handleEmailCCChange}/>
</div>
</div>
<div className="form-group">
<label htmlFor="email-bcc" className="col-sm-1 control-label">BCC</label>
<div className="col-sm-11">
<input type="email"
className="form-control"
id="email-bcc"
value={this.state.emailBCC}
onChange={this.handleEmailBCCChange}/>
</div>
</div>
<div className="form-group">
<label htmlFor="email-subject" className="col-sm-1 control-label">Subject</label>
<div className="col-sm-11">
<input type="email"
className="form-control"
id="email-subject"
value={this.state.emailSubject}
onChange={this.handleEmailSubjectChange}/>
</div>
</div>
</form>
</div>
</div>
</div>
<div className="panel-body">
<Editor onChange={this.handleEditorChange}
body={this.state.emailBody} />
</div>
<div className="panel-footer">
<div className="btn-toolbar pull-right" role="toolbar">
<div className="btn-group" role="group">
<button type="button" onClick={this.handleCancelClick} className="btn btn-danger">CANCEL</button>
<button type="button" onClick={this.handleSaveClick} className="btn btn-success">SAVE</button>
</div>
<div className="btn-group" role="group">
<button type="button" onClick={this.handleSendClick} className="btn btn-primary outline">SEND</button>
</div>
<Modal ref="modalSend" title="Email sent!" body="Your email has been successfully sent!" />
<Modal ref="modalSave" title="Email saved!" body="Your email has been successfully saved!" />
</div>
<div className="clearfix" />
</div>
</div>
);
},
handleEditorChange: function (emailBody) {
this.setState({ "emailBody": emailBody });
},
handleEmailToChange: function (e) {
this.setState({ "emailTo": e.target.value });
},
handleEmailCCChange: function (e) {
this.setState({ "emailCC": e.target.value });
},
handleEmailBCCChange: function (e) {
this.setState({ "emailBCC": e.target.value });
},
handleEmailSubjectChange: function (e) {
this.setState({ "emailSubject": e.target.value });
},
handleCancelClick: function () {
this.setState({
"emailTo": "",
"emailCC": "",
"emailBCC": "",
"emailSubject": "",
"emailBody": ""
});
},
handleSaveClick: function () {
$(ReactDOM.findDOMNode(this.refs.modalSave)).modal();
},
handleSendClick: function () {
$(ReactDOM.findDOMNode(this.refs.modalSend)).modal();
}
});
var options = {
username: "Michel lompret",
link: "https://google.com",
urlImage: "http://lorempicsum.com/futurama/350/200/1",
title: "React Mailbox Editor"
};
var element = React.createElement(Mailbox, options);
ReactDOM.render(element, document.querySelector('.container'));
</script>
Is there a way to get back my gmail or outlook mails in my mailbox component and send email from it like a real time app ?
From their docs....
https://developers.google.com/gmail/api/guides/push
You would need to setup a watch, then callback when your watch changes...
Also from their docs....
https://developers.google.com/gmail/api/guides/sync

Categories

Resources