Opening a modal in edit with all the value but radio button is not checked while condition is true. What am I doing wrong here and should this.state.value be checked?
import React, { Component } from 'react';
import { MDBContainer, MDBBtn, MDBModal, MDBModalBody, MDBModalFooter, MDBInputGroup } from 'mdbreact';
import InputForm from './productsinputfield';
import Collection from './collectionpopup';
import Product from './productpopup';
import axios from 'axios';
This is the class:
class ModalPage extends Component {
addToArr = [{ id: 1, shippingValue: 20, taxValue: 20, shipingStatus: 0, taxStaus: 1 }]
state = {
modal13: false,
tag_name: 'Rajat Srivastava',
status: false,
valueStatus: false,
quantityStatus: false,
}
// This is the function which is calling in every render what
// I want whenever this will be called on edit then radio buttons
// should be checked:
componentDidMount() {
// The Props Data Is Coming From Another Component
if (this.props.sendRowData) {
// This condition is true but still unable to checked radio button:
if(this.props.sendRowData.cart_status == 1){
this.setState({ valueStatus : true });
}else if(this.props.sendRowData.cart_status == 2){
this.setState({quantityStatus : true});
}
}
}
showPopUP(nr) {
let modalNumber = 'modal' + nr
this.setState({
...this.state,
[modalNumber]: !this.state[modalNumber],
status: !this.state.status,
});
this.setState({ name: 'Rajat Srivastava' });
}
This is my JSX code
render() {
return (
<div className="row">
<div className="col-lg-2"></div>
<div className="col-lg-8">
<MDBContainer>
<MDBBtn color="primary" className="floatDiv" onClick={() => this.showPopUP(13)}>
Create Discount Tag
</MDBBtn>
{
this.state.status && <MDBModal isOpen={this.state.modal13} toggle={() => this.showPopUP(13)} size="lg">
<MDBModalBody>
<MDBContainer size="lg">
<form action="#" onSubmit={this.saveTagSettings}>
<h6>Set Products <span style={{ color: "red" }}> * </span></h6><br />
<div className="card card-header">
<div className="form-check card-header">
<div className="marginLeft">
<input className="form-check-input" type="radio" name="product" id="product" checked={this.state.valueStatus} value="1" onChange={(e) => this.handleProductRadio(e, 'minCartVal')} />
<label className="form-check-label" htmlFor="product">
Minimum Cart Value
</label>
</div>
</div>
<div className="form-check card-header">
<div className="marginLeft">
<input className="form-check-input" type="radio" name="product" id="product" checked={this.state.quantityStatus} value="2" onChange={(e) => this.handleProductRadio(e, 'minCartQua')} />
<label className="form-check-label" htmlFor="product">
Minimum Cart Quantity
</label>
</div>
</div>
</div>
<MDBBtn color="primary" type="submit">Save Tag</MDBBtn>
</form>
</MDBContainer>
</MDBModalBody>
<MDBModalFooter>
<MDBBtn color="secondary" onClick={() => this.showPopUP(13)}>
Close
</MDBBtn>
</MDBModalFooter>
</MDBModal>
}
</MDBContainer>
</div>
<div className="col-lg-2"></div>
</div>
);
}
}
export default ModalPage;
Related
I´m currently doing a userinformations component with various required textfields (by material ui).
At the bottom the user has the options to go one step back (cancel the submission) or go to the next step (at the end the user will pay for a service).
Component looks like this:
<>
<CustomizeYourAudit />
<form onSubmit={() => setPaymentStep(2)}>
<AuditInfo auditInfo={auditInfo} setAuditInfo={setAuditInfo} />
{/***************** buttons at the bottom of the payment modal ****************/}
<div className="p-4 flex justify-center">
<button
type="button"
className="order-btn-back"
onClick={() => setShowPaymentModal(false)}>
Cancel
</button>
<span className="px-3" />
<button type="submit" className="order-btn-next">
Next
</button>
</div>
</form>
{/***************** buttons at the bottom of the payment modal END ****************/}
</>
In the auditinfo component I have the following code (ignore the react dropzone):
import { useDropzone } from 'react-dropzone';
import { TextField } from '#mui/material/';
import DragAccepted from './DragAccepted';
import DragRejected from './DragRejected';
import DragInactive from './DragInactive';
import ImagePreview from './ImagePreview';
import './imageDropzone.scss';
interface AuditInfoProps {
auditInfo: AuditInfoType;
setAuditInfo: React.Dispatch<React.SetStateAction<AuditInfoType>>;
}
const AuditInfo = ({ auditInfo, setAuditInfo }: AuditInfoProps) => {
const {
isDragActive,
isDragAccept,
isDragReject,
getRootProps,
getInputProps
} = useDropzone({
accept: {
'image/png': ['.png'],
'image/jpeg': ['.jpg', '.jpeg']
},
maxFiles: 1,
multiple: false,
onDrop: (acceptedFiles) => {
setAuditInfo((prevState) => ({
...prevState,
projectLogo: acceptedFiles.map((file) =>
Object.assign(file, {
preview: URL.createObjectURL(file)
})
)
}));
}
});
return (
<div>
{/***************** Imagedropzone ****************/}
<div className="lg:grid lg:grid-cols-3 justify-around border-b-2">
<div className="border-r-2 p-3 m-auto">
<div
{...getRootProps({
className: 'dropzone-upload-wrapper rounded-lg '
})}>
<input {...getInputProps()} />
<div className="dropzone-inner-wrapper dropzone-inner-wrapper-alt rounded-lg p-8">
{isDragAccept && <DragAccepted />}
{isDragReject && <DragRejected />}
{!isDragActive && <DragInactive />}
</div>
</div>
</div>
<div className="lg:col-span-2 m-auto">
{auditInfo.projectLogo != false ? (
<ImagePreview files={auditInfo.projectLogo} />
) : (
<p className="text-center">Image preview will be shown here</p>
)}
</div>
</div>
{/***************** Imagedropzone End ****************/}
{/***************** Project name and title ****************/}
<div className="p-6 rounded">
<TextField
value={auditInfo.projectName}
id="outlined-basic"
type="text"
label="Project Name"
variant="outlined"
required
onChange={(e) =>
setAuditInfo((prevState) => ({
...prevState,
projectName: e.target.value
}))
}
sx={{ marginBottom: '1.5rem' }}
/>
<TextField
value={auditInfo.projectDescription}
fullWidth
type="text"
id="outlined-basic"
label="Project Description"
multiline
rows="6"
variant="outlined"
required
onChange={(e) =>
setAuditInfo((prevState) => ({
...prevState,
projectDescription: e.target.value
}))
}
/>
</div>
{/***************** Project name and title End ****************/}
</div>
);
};
export default AuditInfo;
So the code actually works perfectly fine and I can´t click the submit button, until I have filled in the required fields.
Any idea what could be wrong here?
Cheers!
I'm watching a Pluralsight course.
At work, I am using React with Sharepoint Online. I have a page which renders a component eg labels, textboxes, people picker and don't have a command document.getElementbyID. Does Sharepoint online work differently to the Pluralsight course playground jscomplete.com
Here is my code. I've removed company sensitive information.
The code works. I just want to understand why I've not had to use document.getElementbyID.
```
import * as React from 'react';
import styles from './FinanceAccReq.module.scss';
import { IFinanceAccReqProps } from './IFinanceAccReqProps';
import { IFinanceAccReqState } from './IFinanceAccReqState';
import {IComboBoxTogglesExampleState}from './IComboBoxTogglesExampleState';
// #pnp/sp imports
import { sp } from '#pnp/sp';
import { PeoplePicker, PrincipalType } from "#pnp/spfx-controls-react/lib/PeoplePicker";
import { getGUID } from "#pnp/common";
import { DefaultButton } from 'office-ui-fabric-react/lib/Button';
import { autobind } from 'office-ui-fabric-react';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { TextField,MaskedTextField } from 'office-ui-fabric-react/lib/TextField';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
import { Stack, IStackTokens } from 'office-ui-fabric-react/lib/Stack';
import { getId } from 'office-ui-fabric-react/lib/Utilities';
import { WebPartContext } from '#microsoft/sp-webpart-base';
import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';
import { bool } from 'prop-types';
//import { IOfficeFabricProps } from '../IOfficeFabricProps';
import { DetailsList, DetailsListLayoutMode, Selection, IColumn } from 'office-ui-fabric-
react/lib/DetailsList';
import { MarqueeSelection } from 'office-ui-fabric-react/lib/MarqueeSelection';
import { ComboBox, Fabric, IComboBoxOption, mergeStyles,IComboBoxProps,
SelectableOptionMenuItemType,PrimaryButton} from 'office-ui-fabric-react/lib/index';
import {SPData} from './SPData';
import { TagPicker, IBasePicker, ITag } from 'office-ui-fabric-react/lib/Pickers';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
const rootClass = mergeStyles({
maxWidth: 500
});
export default class financeAccReq extends React.Component<IFinanceAccReqProps,
IFinanceAccReqState,IComboBoxTogglesExampleState> {
private INITIAL_OPTIONS: ITag[] = [];
private _picker = React.createRef<IBasePicker<ITag>>();
constructor(props: IFinanceAccReqProps, state: IFinanceAccReqState) {
super(props);
//super();
this.handleFirstName = this.handleFirstName.bind(this);
this.handleSurName = this.handleSurName.bind(this);
this.handleWindowsID = this.handleWindowsID.bind(this);
this.handleEmail = this.handleEmail.bind(this);
this.handleCostCentreCode=this.handleCostCentreCode.bind(this);
this.handleTeamName=this.handleTeamName.bind(this);
//this._onCheckboxChange = this._onCheckboxChange.bind(this);
this._system1=this._system1.bind(this);
this.system2=this._system2.bind(this);
this.state = {
addUsers: [],
firstName: "",
surName: "",
windowsID:"",
costCentreCode:"",
email:"",
teamName:"",
titleError:"",
firstNameError: "",
surNameError: "",
windowsIDError:"",
costCentreCodeError:"",
lineManagerError:"",
emailError:"",
selectedItems: [],
dpselectedItem: undefined,
dpselectedCostCentre:undefined,
dpisystem1:undefined,
dpisystem2:false,
costCentreList:[],
INITIAL_OPTIONS: [],
confirmationMessage: ""
};
}
public componentDidMount(){
this.INITIAL_OPTIONS = [];
sp.web.lists.getByTitle("CostCentres").items.getAll().then((result: any)=>{
for(let i: number = 0; i< result.length; i++) {
const b: SPData = result[i];
//const c: IComboBoxOption={key:b.Column1, text: b.CostCentreInfo};
const c: ITag={key:b.Column1, name: b.CostCentreInfo};
this.INITIAL_OPTIONS.push(c);
}
});
}
public render(): React.ReactElement<IFinanceAccReqProps>
{
//const { dpselectedItem, dpselectedItems } = this.state;
const { dpselectedItem } = this.state;
const { dpselectedCostCentre} = this.state;
//const { dynamicErrorValue} = this.state;
const { System1Approver } = this.state;
const stackTokens: IStackTokens = { childrenGap: 1 };
const { system1,system2} = this.state;
const { firstName, surName } = this.state;
const maskFormat: { [key: string]: RegExp } = {'*': /[0-9]/};
const wrapperClassName = mergeStyles({
display: 'flex',
selectors: {
'& > *': { marginRight: '20px' },
'& .ms-ComboBox': { maxWidth: '300px' }
}
});
return (
<div className={ styles.financeAccReq }>
<div className={ styles.container }>
<div className={ styles.row }>
<div className={ styles.column }>
{/* <span className={ styles.title }>Welcome to SharePoint!</span> */}
<p className={ styles.subTitle }>This form should be completed by the new user’s line manager. You will be e-mailed to confirm the user has been set up as requested.</p>
<p className={ styles.subTitle }>If you have any questions regarding this form please contact your Finance Business Partner.</p>
<p className={ styles.subTitle }>It can take up to 5 working days to complete the setup process, failure to complete mandatory fields may result in a further delay.</p>
<div className="ms-Grid-col ms-u-m4 block">
{/* <div className="errorMessage">
<TextField defaultValue="" errorMessage={this.state.confirmationMessage} />
</div> */}
<label className="ms-Label">Title</label>
</div>
<div className="ms-Grid-col ms-u-m8 block">
<Dropdown
//placeHolder="Select an Option"
//label="Title"
id="component"
selectedKey={dpselectedItem ? dpselectedItem.key : undefined}
//ariaLabel="Title"
options={[
{ key: 'Please select', text: 'Please select' },
{ key: 'Mr', text: 'Mr' },
{ key: 'Mrs', text: 'Mrs' },
{ key: 'Ms', text: 'Ms' },
{ key: 'Dr', text: 'Dr' }
]}
errorMessage={this.state.titleError}
onChanged={this._changeTitleState}
onFocus={this._log('onFocus called')}
onBlur={this._log('onBlur called')}
/>
</div>
<div className="ms-Grid-col ms-u-m4 block">
<label className="ms-Label">First Name *</label>
</div>
<div className="ms-Grid-col ms-u-m8 block">
<TextField value={this.state.firstName} onChanged={this.handleFirstName} errorMessage={this.state.firstNameError}/>
</div>
<div className="ms-Grid-col ms-u-m4 block">
<label className="ms-Label">Surname *</label>
</div>
<div className="ms-Grid-col ms-u-m8 block">
<TextField value={this.state.surName} onChanged={this.handleSurName} errorMessage={this.state.surNameError}/>
</div>
<div className="ms-Grid-col ms-u-m4 block">
<label className="ms-Label">Windows id is the user id you use to log on to your PC/Laptop e.g. smitha</label>
<p></p>
<label className="ms-Label">Windows ID * </label>
</div>
<div className="ms-Grid-col ms-u-lg block">
<TextField value={this.state.windowsID} onChanged={this.handleWindowsID} errorMessage={this.state.windowsIDError} />
</div>
<div className="ms-Grid-col ms-u-m4 block">
<label className="ms-Label">Cost Centre Code *</label>
</div>
<div className="ms-Grid-col ms-u-m4 block">
<TagPicker
componentRef={this._picker}
onResolveSuggestions={this._onFilterChangedNoFilter}
onItemSelected={this._onItemSelected}
getTextFromItem={this._getTextFromItem}
pickerSuggestionsProps={{
suggestionsHeaderText: 'Suggested Tags',
noResultsFoundText: 'No Color Tags Found'
}}
itemLimit={1}
disabled={false}
inputProps={{
onBlur: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onBlur called'),
onFocus: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onFocus called'),
'aria-label': 'Tag Picker'
}}
/>
</div>
<div className="ms-Grid-col ms-u-m4 block">
<label className="ms-Label">Email *</label>
</div>
<div className="errorMessage">
<TextField defaultValue="#xxx.org.uk" value={this.state.email} onChanged={this.handleEmail} errorMessage={this.state.emailError} />
</div>
<div className="ms-Grid-col ms-u-m4 block">
<label className="ms-Label">Line Manager *</label><br />
</div>
<PeoplePicker
context={this.props.context}
titleText=""
personSelectionLimit={1}
groupName={""} // Leave this blank in case you want to filter from all users
showtooltip={true}
isRequired={true}
disabled={false}
ensureUser={true}
selectedItems={this._getPeoplePickerItems}
showHiddenInUI={false}
principalTypes={[PrincipalType.User,PrincipalType.SharePointGroup]}
errorMessageClassName="ms-Grid-col ms-u-m8 block"
errorMessage={this.state.lineManagerError}
resolveDelay={1000} />
<div className="ms-Grid-col ms-u-m4 block">
<label className="ms-Label">Team Name (for users of ...)</label>
</div>
<div className="errorMessage">
<TextField value={this.state.teamName} onChanged={this.handleTeamName} />
</div>
<Stack tokens={stackTokens}>
<Toggle inlineLabel onText="Access Required" offText=" Access Not Required" onChange= {this._changeSystem1UserState} />
<Toggle inlineLabel onText="Approval Required" offText="Approval Not Required" onChange= {this._changeSystem2ApproverState} />
</Stack>
<DefaultButton
color="blue"
className="button"
data-automation-id="addSelectedUsers"
title="Submit"//Add Selected User"
onClick={this.addSelectedUsers}>
Submit
</DefaultButton>
</div>
</div>
</div>
</div>
);
}
```
In your code, we don't need use document.getElementById to get the DOM elements.
If you want to use it, we can add some code in the componentDidMount() method in react SPFx web part.
Example:
public render(): React.ReactElement<IFinanceAccReqProps> {
return (
<div className={ styles.financeAccReq }>
<div className={ styles.container }>
<div className={ styles.row }>
<input type="button" className={styles.button} value="Mytest" id="btnSubmit"/>
</div>
</div>
</div>
);
}
public componentDidMount(){
let btnTest=document.getElementById("btnSubmit") as HTMLInputElement;
alert(btnTest.value);
}
More example solutions about SPFx web part for your reference.
SharePoint Framework Client-Side Web Part Samples & Tutorial Materials
Below is the button group component which I used inside the form.How to implement the onchange functions to this button group.I have no Idea how to set the onchange method
import React, {Component} from "react";
import {Popover, OverlayTrigger} from 'react-bootstrap';
import "./ButtonGroup.scss";
const popoverBottom = () =>{
return (
<Popover className="tooltip-popover" title="Here is the where you
give a tooltip">
</Popover>
);
}
export const ButtonGroup = ({
tooltip,
label,
options,
selected,
lableStyle = {},
Title = "Tooltip on top",
}) => {
return (
<div className="nuclei-group">
<p className="nuclei-buttongroup-input"> {label} </p>
<div data-toggle="buttons">
{options.map((option, i) => {
const className = selected == option.value ? "active" : "";
return (
<label
key={i}
style={lableStyle}
className={`btn btn-default nuclei-selection-option ${className}`}
>
<input
type="radio"
name={"name"}
id={option.value}
autoComplete="off"
/>
{option.label}
</label>
);
})}
{tooltip ? (
<span>
<OverlayTrigger trigger="click" rootClose placement="bottom" overlay={popoverBottom()}>
<button type="button" className="btn nuclei-tooltip">?</button>
</OverlayTrigger>
</span>
) : null}
</div>
</div>
);
};
export default ButtonGroup;
then I tried to add on change as below and after submitting the form it doesn't work can somebody help me to resolve it.Normally inside a input tag it works but here? and let me know is this the best way to get values from a form as in the code below
import React, {Component} from "react";
import "./classic-quote.scss";
import {Button, ButtonGroup, InputText} from "../../../components";
import StepBreadcrumb from "../../../components/StepBreadcrumb";
import HeaderTitle from "../../../components/HeaderTitle";
import axios from 'axios';
export default class ClassicQuote extends Component {
constructor(props){
super(props);
this.state = {
insurance_type:'',
vehicle_registration:'',
lease_loan_hire:'',
estimated_market_value:'',
usage:'',
make:'',
model:'',
year:'',
claim_bonus_year:''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange1 = this.handleChange1.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
this.handleChange3 = this.handleChange3.bind(this);
this.handleChange4 = this.handleChange4.bind(this);
}
handleChange1(e){
this.setState({
make: e.target.value
})
}
handleChange2(e){
this.setState({
model: e.target.value
})
}
handleChange3(e){
this.setState({
year: e.target.value
})
}
handleChange4(e){
this.setState({
insurance_type: e.target.id
})
}
handleSubmit(e){
e.preventDefault();
const quotation = {
make: this.state.make,
model: this.state.model,
year: this.state.year,
insurance_type: this.state.insurance_type
}
console.log('gggggggg'+quotation.make+quotation.model+quotation.year+quotation.insurance_type);
let uri = '/items'
axios.post(uri,quotation).then(response => {
console.log('ela');
}).then(error => {
console.log(error);
});
}
render() {
return <div>
{/* <StepBreadcrumb id="bred" /> */}
<div className="container insureme-form zero-padding">
<form onSubmit={this.handleSubmit}>
<div className="row">
<HeaderTitle mainFirstWord="Insurance" restOfTitle="Detail" headerStyle={{fontWeight: "bold"}} headerIcon={true} />
<div className="nuclei-insurance-detail-step-one">
<div className="col-md-12 col-sm-12 col-xs-12">
<ButtonGroup onChange={this.handleChange4} label="" selected="full" options={[{label: "Full Insurance", value: "full"}, {label: "3rd Party Insurance", value: "3rd"}]} tooltip />
<pre>{JSON.stringify(this.state, '', 2)}</pre>
</div>
<div className="col-md-12 col-sm-12 col-xs-12">
<ButtonGroup label="Do you have a vehicle registration No?" selected="Yes" options={[{label: "Yes", value: "Yes"}, {label: "No", value: "No"}]} tooltip />
</div>
<div className="col-md-12 col-sm-12 col-xs-12">
<ButtonGroup label="Do you have any lease,Loan or hire on vehicle?" selected="Yes" options={[{label: "Yes", value: "Yes"}, {label: "No", value: "No"}]} tooltip />
</div>
<div className="col-md-4 col-sm-4 col-xs-8">
<InputText label={"Estimated Market Value?"} placeholder="Rs." />
</div>
<div className="col-md-12 col-sm-12 col-xs-12">
<ButtonGroup label="Usage?" selected="Private" options={[{label: "Private", value: "Private"}, {label: "Hire", value: "Hire"}, {label: "Rent", value: "Rent"}]} tooltip />
</div>
<div className="col-md-12 col-sm-12 col-xs-12 form-group input-text ">
<label>Make, Model and Year of Manufacture? </label>
<div className="col-md-4 col-sm-4 col-xs-4 zero-padding-left">
<input type="text" className="form-control" id={"make-manufacture"} placeholder={"Make"} onChange={this.handleChange1} />
</div>
<div className="col-md-3 col-sm-3 col-xs-4 zero-padding-left">
<input type="text" className="form-control" id={"model-manufacture"} placeholder={"Model"} onChange={this.handleChange2}/>
</div>
<div className="col-md-2 col-sm-2 col-xs-3 zero-padding-left">
<input type="text" className="form-control" id={"year-manufacture"} placeholder={"Year"} onChange={this.handleChange3}/>
</div>
</div>
<div className="col-md-12 col-sm-12 col-xs-12 form-group input-text">
<label>No Claims Bonus?</label>
<div className="col-md-4 col-sm-4 col-xs-8 zero-padding-left">
<InputText tooltip placeholder="No. of Years" />
</div>
</div>
<div className="col-md-12 col-sm-12 col-xs-12">
<Button type="submit" color="red" className="nuclei-bottom-red-button">
Get a Quick Quote
</Button>
<Button type="clear" color="gray" className="nuclei-bottom-gray-button">
Clear
</Button>
</div>
</div>
</div>
</form>
</div>
</div>;
}
}
I tried several ways can get only the make model and year values as printed in the console log
if you want to pass an handler like this:
onChange={this.handleChange4}
you have to add it to the props you receive in Component:
export const ButtonGroup = ({
onChange,
tooltip,
label,
options,
selected,
lableStyle = {},
Title = "Tooltip on top",
}) => {
...
and then in the input elements call onChange:
<input
onChange={onChange}
type="radio"
name={"name"}
id={option.value}
autoComplete="off"
/>
If you want to see the complete solution, I build it in sandbox: Full example here
I saw that you update the form, but you didn't add "onChange" in the ButtonGroup Component file like in the comment:
export const ButtonGroup = ({
onChange, <---this
tooltip,
label,
options,
selected,
lableStyle = {},
Title = "Tooltip on top",
}) => {
return (
<div className="nuclei-group">
<p className="nuclei-buttongroup-input"> {label} </p>
<div data-toggle="buttons">
{options.map((option, i) => {
const className = selected == option.value ? "active" : "";
return (
<label
key={i}
style={lableStyle}
className={`btn btn-default nuclei-selection-option ${className}`}
>
<input
onChange={onChange} <---this
type="radio"
name={"name"}
id={option.value}
autoComplete="off"
/>
{option.label}
</label>
);
})}
I have a basic login form, I have implemented the form validation using material UI.
The validation is visible even when there is a value in the text box.
code:
LoginComponent
import React from "react";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
export class loginComponent extends React.Component {
constructor() {
super();
this.state = {
username: "",
usernameError: "",
password: "",
passwordError:""
};
};
onChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
validate = () => {
let isError = false;
const errors = {
usernameError: "",
passwordError: ""
};
if (this.state.username.trim.length === 0) {
isError = true;
errors.usernameError = "Username is required";
}
if (this.state.password.trim.length === 0) {
isError = true;
errors.passwordError = "password is required";
}
this.setState({
...this.state,
...errors
});
return isError;
}
onSubmit = e => {
e.preventDefault();
const error = this.validate();
if (!error) {
console.log(this.state);
}
};
render() {
return (
<div className="container">
<div id="loginbox" style={{ marginTop: 50 }} className="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div className="panel panel-info">
<div className="panel-heading">
<div className="panel-title">Sign In</div>
</div>
<div style={{ paddingTop: 30 }} className="panel-body">
<form id="loginform" className="form-horizontal" role="form">
<div style={{ marginBottom: 25 }} className="input-group">
<span className="input-group-addon"><i className="glyphicon glyphicon-user"></i></span>
<TextField
name="username"
floatingLabelText="User name"
value={this.state.username}
onChange={e => this.onChange(e)}
errorText={this.state.usernameError}
floatingLabelFixed
/>
</div>
<div style={{ marginBottom: 25 }} className="input-group">
<span className="input-group-addon"><i className="glyphicon glyphicon-lock"></i></span>
<TextField type="password"
name="password"
value={this.state.password}
floatingLabelText="password"
onChange={e => this.onChange(e)}
errorText={this.state.passwordError}
floatingLabelFixed
/>
</div>
<div style={{ paddingTop: 10 }} className="form-group">
<div className="col-sm-12 controls">
<RaisedButton label="Login" onClick={e => this.onSubmit(e)} primary />
</div>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
This are basic required length validation that is still getting fired even after entering the values in text box, can someone suggest what i did wrong.
I think with your comparison:
this.state.password.trim.length will always return 0 as it calculating length of password.trim.
Use this.state.password.trim().length which will trim passowrd value and return its length.
import React, { Component } from 'react';
class BigText extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
text: '',
summary: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<div>
<div>
<div className="row animated fadeIn">
<div className="px-1" style={{ width:100 + '%' }}><br />
<div className="mb-1">
<input type="text"
className="form-control"
placeholder="Title"
name="title"
value={this.state.title}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Text"
name="text"
value={this.state.text}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Summary"
name="summary"
value={this.state.summary}
onChange={this.handleInputChange}
/>
</div>
</div>
<div>
</div>
</div>
</div>
</div>
)
}
}
export default BigText;
import React, { Component } from 'react';
import BigText from './bigText.js';
import InboxStyle from './inboxStyle.js';
import ImageStyle from './imageStyle.js';
import BigTextMobile from './bigText.mobile.js';
import InboxStyleMobile from './inboxStyle.mobile.js';
import ImageStyleMobile from './imageStyle.mobile.js';
class BasicNotification extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleClick = this.handleClick.bind(this);
}
static contextTypes = {
router: React.PropTypes.object
}
handleClick() {
this.context.router.push('/notifications');
}
handleChange(event) {
this.setState({value: event.target.value});
}
checkRadio =(e) =>{
if(e.target.checked) {
this.setState({layout: e.target.value});
}
}
render() {
return (
<div>
<div>
<h1 className="px-2">Create Notification</h1>
<hr />
<div className="row px-1 py-2 animated fadeIn">
<div className="px-1 mr-2" style={{ width:50 + '%' }}><br />
<div className="mb-1">
<input type="text"
className="form-control"
placeholder="Title"
name="title"
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Text"
name="text"
/>
</div>
<div>
<select placeholder="Logo" className="form-control" onChange={this.handleChange}>
<option default>Select Logo</option>
<option>Default</option>
<option>Custom</option>
</select>
</div>
<div><br />
<div className="btn-group" data-toggle="buttons">
<label className="btn btn-css btn-outline-secondary">
<input type="radio" name="layout" value="image" onChange={this.checkRadio}/>ImageStyle
</label>
<label className="btn btn-css btn-outline-secondary">
<input type="radio" name="layout" value="big" onChange={this.checkRadio}/>BigText
</label>
<label className="btn btn-css btn-outline-secondary">
<input type="radio" name="layout" value="inbox" onChange={this.checkRadio}/>InboxStyle
</label>
</div>
{
(this.state.layout === "big")?
<BigText/>:
(this.state.layout === "image")?
<ImageStyle/>:
(this.state.layout === "inbox")?
<InboxStyle/>:
null
}
<br />
<div className="row px-1" >
<div>
<button className="nav-link btn btn-block btn-info" onClick={this.handleClick} >Save</button>
</div>
<div className="px-1">
<button className="nav-link btn btn-block btn-danger"> Cancel</button>
</div>
</div>
</div><br />
</div>
<div>
{
(this.state.layout === "big")?
<BigTextMobile text={this.state.text} summary={this.state.summary} title={this.state.title}/>:
(this.state.layout === "image")?
<ImageStyleMobile/>:
(this.state.layout === "inbox")?
<InboxStyleMobile/>:
null
}
</div>
</div>
</div>
</div>
)
}
}
export default BasicNotification;
This is the screen i made on which I had imported three files which will be shown on clicking radio buttons.
Also there is a relevant mobile screen as well shown aside
now for example i imported as you can see BigText , it is containing the form
Now i want to print its input values in BigTextMobile Component
To simplify the solution you can do something like this:
<BigText onChange={data => {this.setState({ data })}} />
In the BigText component then you can put some data via this callback like this:
handleInputChange(event) {
const data = {
[event.target.name]: event.target.value
};
this.setState(data );
this.props.onChange(data);
}
And transfer this data to your BigTextMobile component from state:
<BigTextMobile data={this.state.data} ... />