Using React with Sharepoint Online Part 1 - reactjs

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

Related

How to Store Choose File Image to Local Storage with React Hooks

I am building a profile page but i have some problems with storing the profile image to browser local storage. I choose the file from my device and upload it. but when i refresh the page, it s gone.
below is my code below and also a visual of the page. the local storage function works for everything in the page except for the image. what is the problem here ?
If you can help i will be so glad.
useLocalStorage.js
import React from "react"
import { useState, useEffect } from "react";
function getStorageValue(key, defaultValue) {
// getting stored value
const saved = localStorage.getItem(key);
const initial = JSON.parse(saved);
return initial || defaultValue;
}
export const useLocalStorage = (key, defaultValue) => {
const [value, setValue] = useState(() => {
return getStorageValue(key, defaultValue);
});
useEffect(() => {
// storing input name
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
};
formikData.js
import * as Yup from "yup";
const initialValues = {
fullname: "",
email: "",
phone: "",
bio: "",
city: "",
state: "",
street: "",
zip: "",
};
const yupValidation = {
phone: Yup.number().required("Phone is Required"),
bio: Yup.string().required("Bio is Required"),
city: Yup.string().required("City is Required"),
state: Yup.string().required("State is Required"),
street: Yup.string().required("Street is Required"),
};
export { initialValues, yupValidation };
PersonalDetails.js
import React, { useState, useEffect } from "react";
import { Col, Row, Container, Alert } from "react-bootstrap";
import poodle from "../../images/poodle.jpg";
import { Formik, Field, Form, ErrorMessage } from "formik";
import { initialValues, yupValidation } from "./formikData";
import * as Yup from "yup";
import cities from "../../data/cities";
import "./PersonalDetails.css";
import { useSelector } from "react-redux";
import { db } from "../../firebase";
import { useLocalStorage } from "./useLocalStorage";
import { useTranslation } from "react-i18next";
const PersonalDetails = () => {
const user = useSelector((state) => state.user);
const [fullname, setFullname] = useLocalStorage("fullname", "");
const [email, setEmail] = useLocalStorage("email", "");
const [bio, setBio] = useLocalStorage("bio", "")
const [phone, setPhone] = useLocalStorage("phone", "");
const [city, setCity] = useLocalStorage("city", "");
const [state, setState] = useLocalStorage("state", "");
const [street, setStreet] = useLocalStorage("street", "");
const [zip, setZip] = useLocalStorage("zip", "");
const [alertShown, isAlertShown] = useState(false);
const [picture, setPicture] = useLocalStorage("picture", poodle);
const onChangePicture = e => {
setPicture(URL.createObjectURL(e.target.files[0]));
};
const clearInfo = () => {
setBio("")
setPhone("")
setCity("")
setState("")
setStreet("")
setZip("")
setPicture("");
}
const fetchUserName = async () => {
try {
const query = await db
.collection("profile")
.where("uid", "==", user.uid)
.get();
const data = await query.docs[0].data();
setFullname(data.name);
setEmail(data.email);
} catch (err) {
console.error(err);
alert("An error occured while loading user data");
}
};
useEffect(() => {
if(user) fetchUserName();
}, [user]);
const { t } = useTranslation();
return (
<Container fluid className="mainContainer profile">
<Container className="pt-3 pb-4">
<Row>
<Col lg="4" md="12">
<div class="bgWhite fullHeight">
<img
src={picture}
alt=""
width="120"
height="120"
className="align-items-center mb-4 avatar"
/>
<input className="mb-5" id="profilePic" type="file" onChange={onChangePicture} />
<h5 className="mb-2 text-uppercase newColor">
{fullname}
</h5>
<p className="newColor">
{email}
</p>
<p className="profileInfo">
Tel: {''}
<span>{phone}</span>
</p>
<p className="profileInfo">
{t("personalPage.sideText0")} : {''}
<span>{city}</span>
</p>
<p className="profileInfo">
{t("personalPage.sideText1")} : {''}
<span>{state}</span>
</p>
<p className="profileInfo">
{t("personalPage.sideText2")} : {''}
<span>{street}</span>
</p>
<p className="profileInfo">
{t("personalPage.sideText3")} : {''}
<span>{zip}</span>
</p>
{bio && (
<h4 className="mb-2 mt-4 newColor">About</h4>
)}
<p className="profileInfo">
Bio: {''}
<span>{bio}</span>
</p>
</div>
</Col>
<Col lg="8" md="12" className="mt-lg-0 mt-5 formSection">
<div className="bgWhite personelInfo" align="left">
{alertShown && (
<Alert variant="success">{t("personalPage.alert0")}</Alert>
)}
<Formik
initialValues={initialValues}
validationSchema={Yup.object(yupValidation)}
onSubmit={(values, { setSubmitting }) => {
isAlertShown(true);
setFullname(values.fullname)
setEmail(values.email);
setBio(values.bio)
setPhone(values.phone)
setCity(values.city)
setState(values.state)
setStreet(values.street)
setZip(values.zip)
}}
>
{(props) => {
const { values } = props;
return (
<>
<Form>
<h3 className="newColor">{t("personalPage.title0")}</h3>
<div className="row d-flex justify-content-around mt-4">
</div>
<div className="row d-flex justify-content-around mt-4">
<div>
<Field
placeholder={t("personalPage.placeholder2")}
type="tel"
name="phone"
className="shadow inputStyle"
/>
<div className="error">
<ErrorMessage name="phone" />
</div>
</div>
<div>
<Field
placeholder={t("personalPage.placeholder3")}
name="bio"
as="textarea"
className="shadow inputStyle"
/>
<div className="error">
<ErrorMessage name="bio" />
</div>
</div>
</div>
<div className="mt-4">
<h3 className="newColor">{t("personalPage.title1")}</h3>
<div className="row d-flex justify-content-around mt-4 ">
<div>
<Field
component="select"
id="city"
name="city"
multiple={false}
className="shadow inputStyle"
>
<option value="">{t("personalPage.dropdown")}</option>
{cities.map((city) => {
return (
<option name="city">{city.name}</option>
);
})}
</Field>
<div className="error">
<ErrorMessage name="city" />
</div>
</div>
<div>
<Field
placeholder={t("personalPage.placeholder5")}
type="text"
name="state"
className="shadow inputStyle"
/>
<div className="error">
<ErrorMessage name="state" />
</div>
</div>
</div>
<div className="row d-flex justify-content-around mt-4 ">
<div>
<Field
placeholder={t("personalPage.placeholder6")}
type="text"
name="street"
className="shadow inputStyle"
/>
<div className="error">
<ErrorMessage name="street" />
</div>
</div>
<div>
<Field
placeholder={t("personalPage.placeholder7")}
type="text"
name="zip"
className="shadow inputStyle"
/>
<div className="error">
<ErrorMessage name="zip" />
</div>
</div>
</div>
<div className="row d-flex mt-5 justify-content-center">
<button
className="m-2 button"
type="submit"
>
{t("personalPage.button0")}{" "}
</button>
<button
className="m-2 button cancelBtn"
onClick={clearInfo}
type="button"
>
{t("personalPage.button1")}{" "}
</button>
</div>
</div>
</Form>
</>
);
}}
</Formik>
</div>
</Col>
</Row>
</Container>
</Container>
);
};
export default PersonalDetails;

How to checked radio button on edit in ReactJs using componentDidMount

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;

Encountered two children with the same key, Objects are not valid as a React child

When I sort through an array of objects and then output them to the options select, I get errors:
Encountered two children with the same key, Objects are not valid as a React child.
Highlighted ---- important fragments below.
import React, { useState } from "react";
import { DatePicker } from "antd";
import BarChartsMonth from "./../../../components/BarCharts/Barchartmonth";
import BarChartsWeek from "./../../../components/BarCharts/Barchartweek";
import "antd/dist/antd.css";
import { Select } from "antd";
const TeamActivity = () => {
const { MonthPicker, WeekPicker } = DatePicker;
const handleChangeView = val => {
setView(val);
};
+++++++++++++++++++++++++++++++++++++++++++++++++++++
const users = [
{ name: "Peter", surname: "Parker" },
{ name: "Edvard", surname: "Rykinozhnici" },
{ name: "Top", surname: "Ragnakek" },
{ name: "Pavel", surname: "Doorov" }
];
++++++++++++++++++++++++++++++++++++++++++++++++++++++
const UsCollection = users.map((user,i)=> {
return (
<Option key={i} value > {user}</Option>
)
})
++++++++++++++++++++++++++++++++++++++++++++++++++++++
const [view, setView] = useState("Month");
return (
<div className="activity-page">
{" "}
<div className="main-title">Activity of the team</div>
<div className="wrapper-wrapper">
<div className="sort-by">Sort by:</div>
<div className="datepickers-wrapper">
<MonthPicker onChange={(date, type) => handleChange(date, "month")} />
<WeekPicker
placeholder="Select week"
onChange={(date, type) => handleChange(date, "week")}
/>
</div>
<div>
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
filterOption={(input, option) =>
option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
+++++++++++++++++++++++++++++++++++++++++
{UsCollection}
+++++++++++++++++++++++++++++++
</Select>
</div>
</div>
<div className="container ">
<h1 className="week-activity"> {view} activity</h1>
<div className="changes-week-month">
<form>
<input
type="radio"
name="state"
id="week-id"
onClick={() => {
handleChangeView("Week");
}}
/>
<label htmlFor="week-id"> Week </label>
<input
type="radio"
name="state"
id="month-id"
defaultChecked={true}
onClick={() => {
handleChangeView("Month");
}}
/>
<label htmlFor="month-id"> Month </label>
</form>
</div>
{view === "Month" ? <BarChartsMonth /> : <BarChartsWeek />}
</div>
</div>
);
};
export default TeamActivity;
Выполнить кодВернуться к сообщению

How to get the value from button group in react component

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

React and typescript using datepicker error cant find module

I was using React and Typescript. I installed react-datepicker and imported into my code. This error occurred:
module can't find react-datepicker
But I have react-datepicker module in node_module. why does the error occure?
I'm using TSX file method.
todo.component.tsx
import * as React from 'react';
import * as classNames from 'classnames';
import TodoList from './todo.list';
import { Todo } from './../todo.interface';
import { Button } from 'react-bootstrap';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
const KEYCODE_ENTER = 13;
export default class TodoComponent extends React.Component
<TodoComponentProps, TodoComponentState> {
constructor(props) {
super(props);
this.state = {
description: '',
valid: true,
items: [], text: '',
startDate: '',
};
this.removeTodos = this.removeTodos.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(date) {
this.setState({
startDate: date
});
}
addTodos(e) {
e.preventDefault();
this.setState({
items: [this.state.text, ...this.state.items],
text: ''
});
}
removeTodos(name, i) {
let items = this.state.items.slice();
items.splice(i, 1);
this.setState({
items
});
}
updateValue(e) {
this.setState({ text: e.target.value })
}
openNav() {
document.getElementById("mySidenav").style.width = "250px";
console.log(this)
}
closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
setDescription(event) {
this.setState({ valid: true, description: event.target.value });
}
addTodo(event) {
if (event && event.keyCode !== KEYCODE_ENTER && event.type !== 'click') {
return;
}
if (!this.state.description.length || this.state.description.length > 50) {
this.setState({ valid: false });
} else {
this.props.addTodo(this.state.description);
this.setState({ description: '' });
}
}
render() {
let inputClass = classNames('form-group', {
'has-error': !this.state.valid
});
return (
<div>
<div className="container" onKeyDown={this.addTodo.bind(this)}>
<div className="row">
<div className="col-sm-12">
<h2 className="text-center">What do you need to do?</h2>
<br />
<br />
</div>
<div className="col-sm-6 col-sm-offset-3">
<div className={inputClass}>
<label className="control-label">Task description</label>
<input className="form-control input-lg" type="text" value={this.state.description} onChange={this.setDescription.bind(this)} />
</div>
</div>
<div className="col-sm-3 col-sm-offset-3">
<button className="btn btn-success btn-block" onClick={this.addTodo.bind(this)}>
<i className="fa fa-plus"></i> Add Todo
</button>
</div>
<div className="col-sm-3">
<button className="btn btn-danger btn-block" onClick={this.props.removeDoneTodos.bind(this)}>
<i className="fa fa-trash-o"></i> Remove done todos
</button>
</div>
</div>
<br />
<br />
<div className="row">
<div className="col-sm-6 col-sm-offset-3" onClick={this.openNav.bind(this)}>
<TodoList {...this.props} />
</div>
</div>
<div id="mySidenav" className="row offcanvas">
<div className="sideNav">
<span onClick={this.closeNav.bind(this)}><i className="fa fa-lg fa-close"></i></span>
<br /><br />
<div className="due">
<DatePicker
inline
selected={this.state.startDate}
onChange={this.handleChange}
/>
</div>
<hr />
<div className="remind">
</div>
<hr />
<div className="sublist" >
<TodosubList items={this.state.items} removeTodos={this.removeTodos} />
<form onSubmit={(e) => this.addTodos(e)}>
<input
placeholder="Add SubTask"
value={this.state.text}
onChange={(e) => { this.updateValue(e) }}
/>
<button type="submit">+</button>
</form>
</div>
<hr />
<div className="description">
</div>
<hr />
<div className="comment">
</div>
<hr />
<div className="commentIn">
</div>
</div>
</div>
</div>
</div>
);
}
}
class TodosubList extends React.Component<{ items?: any; removeTodos: any; }, {}> {
removeItem(item, i) {
this.props.removeTodos(item, i);
}
render() {
return (
<ul className="sub">
{this.props.items.map((todo, i) => {
return <li onClick={() => { this.removeItem(todo, i) }} key={i}>{todo}</li>
})}
</ul>
);
}
}
interface TodoComponentProps {
todos: Todo[];
addTodo(description: string): void;
addTodos?: any;
toggleTodo: React.MouseEventHandler;
editTodo: React.MouseEventHandler;
removeTodo: React.MouseEventHandler;
removeDoneTodos: React.MouseEventHandler;
}
interface TodoComponentState {
description?: string;
subdescription?: any;
valid?: boolean;
items?: any;
text?: any;
startDate?: any;
}
cmd error:
error:cant find module react-datepicker.
I think you need to npm install #types/react-datepicker.

Resources