How can i pass the data inside setState to modal REACTJS - javascript

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>}

Related

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

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

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()
);

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)

Setting Component State after Redux has Mapped Redux State to Props

I am trying to initialize a form with some user information using Redux Forms by pulling the information from my components state. I have a redux action in the componentDidMount method of my component that calls the action, retrieves the information, and then maps a 'profile' object from my store to the components props. The problem is, when I go to setState to update the profile info, it comes back as undefined. I have tried to use the componentWillRecieveProps to see if I can catch the updated 'Profile' props but it is still undefined. Whats the best way to update the component's state once 'this.props.profile' returns the users information?
Here is the component's code:
import React, { Component } from "react";
import { connect } from "react-redux";
import { Field, reduxForm } from "redux-form";
import { Link } from "react-router-dom";
import classnames from "classnames";
import * as actions from "../../actions";
class CreateProfile extends Component {
constructor(props) {
super(props);
this.state = {
showSocialMedia: true,
profile: {}
};
}
componentDidMount() {
this.props.getCurrentUserProfile();
}
// componentDidUpdate(prevProps, prevState) {
// if (prevProps.profile.profile !== this.props.profile.profile) {
// console.log(this.props.profile);
// }
// }
renderField(field) {
return (
<div className="form-group">
<input
className={classnames("form-control form-control-lg", {
"is-invalid": field.meta.touched && !field.meta.valid
})}
type={field.type}
placeholder={field.placeholder}
{...field.input}
/>
<small className="text-muted">{field.description}</small>
<div className="invalid">
{field.meta.touched && !field.meta.valid ? (
<div className="text-center">
<i className="far fa-edit" /> {field.meta.error}
</div>
) : (
""
)}
</div>
</div>
);
}
renderAlert() {
if (this.props.errors.message) {
return (
<div className="alert alert-danger error-message mt-4 text-center">
<h3>
<i className="fas fa-info-circle" />
</h3>
<h6 className="invalid">{this.props.errors.message}</h6>
</div>
);
}
}
renderSelectField(field) {
return (
<div className="form-group">
<select
className={classnames("form-control form-control-lg", {
"is-invalid": field.meta.touched && !field.meta.valid
})}
{...field.input}
>
<option value="" disabled>
* Select a Professional Status
</option>
<option value="Developer">Developer</option>
<option value="Junior Developer">Junior Developer</option>
<option value="Senior Developer">Senior Developer</option>
<option value="Manager">Manager</option>
<option value="Student or Learning">Student or Learning</option>
<option value="Instructor or Teacher">Instructor or Teacher</option>
<option value="Intern">Intern</option>
<option value="Other">Other</option>
</select>
<small className="text-muted">
Give us an idea of where you are at in your career
</small>
<div className="invalid">
{field.meta.touched && !field.meta.valid ? (
<div className="text-center">
<i className="far fa-edit" /> {field.meta.error}
</div>
) : (
""
)}
</div>
</div>
);
}
renderSocialMediaField(field) {
return (
<div className="form-group">
<div className="input-group-prepend">
<span className="input-group-text">
<i className={field.icon} />
</span>
<input
type={field.type}
className="form-control"
placeholder={field.placeholder}
icon={field.icon}
{...field.input}
/>
</div>
</div>
);
}
onSubmit(values) {
this.props.createNewUserProfile(values);
}
toggleHiddenSocialInputs(e) {
e.preventDefault();
this.setState({
showSocialMedia: !this.state.showSocialMedia
});
}
render() {
const { handleSubmit } = this.props;
const { profile } = this.props;
return (
<div className="container">
<div className="row">
<div className="col-md-8 m-auto">
<Link to="/dashboard" className="btn btn-light p-2 mt-2">
<i className="mr-1 fas fa-long-arrow-alt-left" /> Go Back
</Link>
<h5 className="display-4 pt-2 text-center font-weight-light">
Update Your Profile
</h5>
<p className="text-black-50 pt-3 font-weight-light">
* = required field
</p>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
{this.renderAlert()}
<Field
name="handle"
type="text"
placeholder="* Profile handle"
component={this.renderField}
description="A unique handle for your profile URL - (Can't be changed later)"
/>
<Field name="status" component={this.renderSelectField} />
<Field
name="company"
type="text"
placeholder="Company"
component={this.renderField}
description="Can be your own or the one you work for"
/>
<Field
name="website"
type="text"
placeholder="Website"
component={this.renderField}
description="Could be your own or company website"
/>
<Field
name="location"
type="text"
placeholder="Location"
component={this.renderField}
description="Suggested format is: City, State"
/>
<Field
name="skills"
type="text"
placeholder=" Skills"
component={this.renderField}
description="Please use comma separated values (eg: HTML, CSS, Javascript, etc)"
/>
<Field
name="githubusername"
type="text"
placeholder="Github Username"
component={this.renderField}
description="If you want your latest repos and a Github link, include your username"
/>
<div className="form-control-group">
<Field
className="form-control form-control-lg"
name="bio"
placeholder="A short bio about yourself"
component="textarea"
/>
<small className="text-muted">
Tell us a little about yourself
</small>
</div>
<div className="row mt-2 pt-2">
<button
className="btn btn-outline-secondary m-auto"
onClick={this.toggleHiddenSocialInputs.bind(this)}
>
Add Social Network Links <i className=" ml-1 fas fa-users" />
</button>
</div>
{!this.state.showSocialMedia && (
<div className="mt-3">
<Field
name="facebook"
placeholder="Facebook profile URL"
icon="fab fa-facebook-square"
component={this.renderSocialMediaField}
/>
<Field
name="twitter"
placeholder="Twitter profile URL"
icon="fab fa-twitter-square"
component={this.renderSocialMediaField}
/>
<Field
name="linkedin"
placeholder="Linkedin profile URL"
icon="fab fa-linkedin"
component={this.renderSocialMediaField}
/>
<Field
name="youtube"
placeholder="Youtube profile URL"
icon="fab fa-youtube-square"
component={this.renderSocialMediaField}
/>
<Field
name="instagram"
placeholder="Instagram profile URL"
icon="fab fa-instagram"
component={this.renderSocialMediaField}
/>
</div>
)}
<button action="submit" className="btn btn-info btn-block mt-5">
Create Profile <i className=" ml-1 fas fa-user-alt" />
</button>
{this.renderAlert()}
</form>
</div>
</div>
</div>
);
}
}
function validate(values) {
const errors = {};
if (!values.handle) {
errors.handle = "Please enter a handle for your profile";
}
if (!values.status) {
errors.status = "Please select a status for your profile";
}
return errors;
}
const mapStateToProps = state => {
return {
errors: state.errors,
profile: state.profile
};
};
export default reduxForm({
validate,
form: "CreateProfile",
initialValues: {}
})(connect(mapStateToProps, actions)(CreateProfile));
First, I'm not sure why you want to attach profile to component state. But if this.props.profile is always undefined, then it sounds like you're failing to fetch the user profile or you're not updating the store correctly. I would need to see getCurrentUserProfile and your reducer.
Fwiw, I would dispatch a request for user information from a container and set initialValues to state.profile (if state.profile, is in fact, your initial user data).

Want to create a new instance of the component

What i want is that i want to create a new ad which should have the title and desc which user input but when i run the code below it create and [object Object], and why is it showing object instead of the ad please explain
var ValidatePost = React.createClass({
CheckingPost: function() {
var product_title = document.forms["post"]["pro_title"].value;
var product_desc = document.forms["post"]["pro_desc"].value;
var clearForm = document.forms["post"];
var returnAd = <Newad title={product_title} desc={Product_desc} />
var newproduct = document.getElementById("newproduct");
newproduct.innerHTML += returnAd;
clearForm.reset();
},
render: function(){
return(
<div>
<button type="button" className="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" className="btn btn-primary btn-md" id="post-ads" onClick={this.CheckingPost} data-dismiss="modal"><span className="glyphicon glyphicon-pencil"></span> Post Add
</button>
</div>
);
}
});
function Ads(product) {
return(
<div className = "col-sm-6 col-md-4">
<div className = "thumbnail">
<img src={product.image} alt="product-image"/>
</div>
<div className = "caption">
<div className="border">
<h3>{product.title}</h3>
<p>{product.desc}</p>
<button className = "btn btn-primary" role = "button" data-toggle="modal" data-target="#view-detail">View Details
</button>
</div>
</div>
</div>
);
}
function Newad(product) {
return (
<div className="row" id="newproduct">
<Ads title="Forza" desc="rndom text rndom text rndom text rndom text" image="img/img2.jpg" />
<Ads title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum" image="img/img1.jpg" />
<Ads title="Xbox one" desc="Lorem ipsum jipsum Lorem ipsum jipsum" image="img/img3.png" />
<Ads title="MacBook" desc="Lorem ipsum jipsum Lorem ipsum jipsum" image="img/img4.jpg" />
</div>
);
}
function PostModal() {
return (
<form id="post-form" method="POST" name="post">
<div className="modal fade" id="addPostModal" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content" >
<div className="modal-header" >
<button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 className="modal-title" id="exampleModalLabel">Post Your Add</h3>
</div>
<div className="modal-body">
<span id="errorPlace" >
</span>
<div className="form-group">
<label htmlFor="product-title" className="control-label">Title:</label>
<input type="text" placeholder="My Book" className="form-control field-validate" id="product-title" name="pro_title"/>
</div>
<div className="form-group">
<label htmlFor="product-desc" className="control-label">Description:</label>
<textarea className="form-control field-validate" placeholder="Description here . . ." id="product-desc" name="pro_desc"></textarea>
</div>
<div className="form-group">
<label htmlFor="seller-name" className="control-label">
Seller Name:
<i data-toggle="tooltip" title="This can be your or seller name." data-placement="right" className="glyphicon glyphicon-question-sign"></i>
</label>
<input type="text" placeholder="Osama" className="form-control field-validate" id="seller-name" name="sel_name"/>
</div>
<div className="form-group">
<label htmlFor="seller-email" className="control-label">
Seller Email:
<i data-toggle="tooltip" title="This can be your or seller email through which the buyer can contact you" data-placement="right" className="glyphicon glyphicon-question-sign"></i>
</label>
<input type="email" placeholder="someone#somedomain.com" className="form-control field-validate" id="seller-email" name="sel_email"/>
</div>
<div className="form-group">
<label htmlFor="seller-number" className="control-label">
Seller Contact No:
<i data-toggle="tooltip" title="This can be your or seller number through which the buyer can contact you" data-placement="right" className="glyphicon glyphicon-question-sign"></i>
</label>
<input type="number" placeholder="+92" className="form-control field-validate" id="seller-number" name="sel_no"/>
</div>
<div className="form-group">
<label htmlFor="price" className="control-label">
Price:
<i className="glyphicon glyphicon-question-sign"></i>
</label>
<input size="2" type="number" placeholder="66.00" className="form-control field-validate" id="price" name="price"/>
</div>
<div className="form-group">
<label htmlFor="seller-email" className="control-label">
Product Image:
<i data-toggle="tooltip" title="Upload picture of your product" data-placement="right" className="glyphicon glyphicon-question-sign"></i>
</label>
<input type="file" onchange="imgUpload(event, this)" id="product-image" />
<div className="img-wrap-up">
<img id="img-view" src="" />
</div>
</div>
<div id="error-place"></div>
</div>
<div className="modal-footer">
<ValidatePost />
</div>
</div>
</div>
</div>
</form>
);
}

Categories

Resources