i am trying to presist the checkbox using local storage...after applying that...
if i select the one checkbox selecting all checkboxes...i using map function for the checkboxes...can any one help on this.....i want to select individual check box
this is the linkmof code sand box :
https://codesandbox.io/s/sparkling-wind-rmz1z?file=/src/App.js
branches.js
import React, { Component } from "react";
import Checkbox from "#material-ui/core/Checkbox";
import FormGroup from "#material-ui/core/FormGroup";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import { List, ListItem } from "#material-ui/core";
import Button from "react-bootstrap/Button";
// const [isChecked, setIsChecked] = useState(true);
class BranchComponent extends Component {
constructor(props) {
super(props);
this.state = {
value: {},
count: 0,
checked: localStorage.getItem("checkbox") === "true" ? true : false
};
}
CheckedBox = e => {
let checked = e.target.checked;
let count = this.state.count;
if (checked) {
console.log(checked);
this.setState({ checked: true });
count++;
} else {
count--;
console.log(checked);
this.setState({ checked: false });
}
this.setState({ count });
console.log(count);
let values = this.state.value;
values[e.target.value] = e.target.checked;
this.setState({ value: values });
localStorage.setItem("checkbox", e.target.checked.toString());
};
checkBoxSubmit = e => {
e.preventDefault();
console.log(this.state.value);
};
render() {
const arr = ["Branch 1", "Branch 2", "Branch 3"];
return (
<React.Fragment>
<form onSubmit={this.checkBoxSubmit}>
<FormGroup aria-label="position" row>
<List className="courses-college-regis">
{arr.map((a, key) => (
<ListItem button key={key}>
<FormControlLabel
label={a}
value={a}
type="checkbox"
name={a}
checked={this.state.checked}
control={<Checkbox color="primary" />}
onClick={this.CheckedBox}
/>
</ListItem>
))}
</List>
</FormGroup>
Count :{this.state.count}
<br />
<Button type="submit" variant="primary">
Submit
</Button>
</form>
</React.Fragment>
);
}
}
export default BranchComponent;
i updated your code is working fine,
import React, { Component } from "react";
import Checkbox from "#material-ui/core/Checkbox";
import FormGroup from "#material-ui/core/FormGroup";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import { List, ListItem } from "#material-ui/core";
import Button from "react-bootstrap/Button";
var localStorageData = localStorage.getItem("checkbox");
// const [isChecked, setIsChecked] = useState(true);
class BranchComponent extends Component {
constructor(props) {
super(props);
this.state = {
value: {},
count:
localStorageData && typeof JSON.parse(localStorageData) === "object"
? JSON.parse(localStorageData).length
: 0,
checked:
localStorageData && typeof JSON.parse(localStorageData) === "object"
? JSON.parse(localStorageData)
: []
};
}
CheckedBox = (e, index) => {
let checked = e.target.checked;
let count = this.state.count;
var addData = [...this.state.checked, index];
if (checked) {
console.log(checked);
this.setState({ checked: [...new Set(addData)] });
count++;
} else {
count--;
console.log(checked);
addData = addData.filter(find => find !== index);
this.setState({ checked: addData });
}
this.setState({ count: addData.length });
console.log(count);
let values = this.state.value;
values[e.target.value] = e.target.checked;
this.setState({ value: values });
localStorage.setItem("checkbox", JSON.stringify([...new Set(addData)]));
};
checkBoxSubmit = e => {
e.preventDefault();
console.log(this.state.value);
};
render() {
const arr = ["Branch 1", "Branch 2", "Branch 3"];
return (
<React.Fragment>
<form onSubmit={this.checkBoxSubmit}>
<FormGroup aria-label="position" row>
<List className="courses-college-regis">
{arr.map((a, key) => (
<ListItem button key={key}>
<FormControlLabel
label={a}
value={a}
type="checkbox"
name={a}
checked={this.state.checked.includes(a)}
control={<Checkbox color="primary" />}
onClick={e => this.CheckedBox(e, a)}
/>
</ListItem>
))}
</List>
</FormGroup>
Count :{this.state.count}
<br />
<Button type="submit" variant="primary">
Submit
</Button>
</form>
</React.Fragment>
);
}
}
export default BranchComponent;
Related
Good day so I have a question about firebase and perhaps my code as well I wrote some code in JSX and React linked to Firebase and the Button that I'm using to delete is not working properly.
I'm using Parent Child props to pass the function into the page that is needed to be deleted but there is no functionality. I need help thanks!
this is the parent where the function is located :
import React from 'react';
import fire from '../config/firebase';
import Modal from 'react-modal';
// import "firebase/database";
// import 'firebase/auth';
import NotesCard from './note-card';
Modal.setAppElement('#root');
export default class Notes extends React.Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
notes: [],
showModal: false,
loggedin: false
};
this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
this.handleAddNote = this.handleAddNote.bind(this);
this.handleRemoveNote = this.handleRemoveNote.bind(this);
}
componentDidMount() {
this._isMounted = true;
fire.auth().onAuthStateChanged((user) => {
if(user){
// call firebase from import fire
// grab userData and push it to the dataArray
fire.database().ref(`users/${user.uid}/notes`).on('value', (res) => {
const userData = res.val()
const dataArray = []
for(let objKey in userData) {
userData[objKey].key = objKey
dataArray.push(userData[objKey])
}
// set in the state
if(this._isMounted){
this.setState({
notes: dataArray,
loggedin: true
})
}
});
}else {
this.setState({loggedin: false})
}
});
};
componentWillUnmount() {
this._isMounted = false;
}
handleAddNote (e) {
e.preventDefault()
const note = {
title: this.noteTitle.value,
text: this.noteText.value
}
// reference where we can push it
const userId = fire.auth().currentUser.uid;
const dbRef = fire.database().ref(`users/${userId}/notes`);
dbRef.push(note)
this.noteTitle.value = ''
this.noteText.value = ''
this.handleCloseModal()
}
handleRemoveNote(key) {
const userId = fire.auth().currentUser.uid;
const dbRef = fire.database().ref(`users/${userId}/notes/${key}`);
dbRef.remove();
}
handleOpenModal (e) {
e.preventDefault();
this.setState({
showModal: true
});
}
handleCloseModal () {
this.setState({
showModal: false
});
}
render() {
return (
<div>
<button onClick={this.handleOpenModal}>create Note</button>
<section className='notes'>
{
this.state.notes.map((note, indx) => {
return (
<NotesCard
note={note}
key={`note-${indx}`}
handleRemoveNote={this.handleRemoveNote}
/>
)
}).reverse()
}
</section>
<Modal
isOpen={this.state.showModal}
onRequestClose={this.handleCloseModal}
shouldCloseOnOverlayClick={false}
style={
{
overlay: {
backgroundColor: '#9494b8'
},
content: {
color: '#669999'
}
}
}
>
<form onSubmit={this.handleAddNote}>
<h3>Add New Note</h3>
<label htmlFor='note-title'>Title:</label>
<input type='text' name='note-title' ref={ref => this.noteTitle = ref} />
<label htmlFor='note-text'>Note</label>
<textarea name='note-text' ref={ref => this.noteText = ref} placeholder='type notes here...' />
<input type='submit' onClick={this.handleAddNote} />
<button onClick={this.handleCloseModal}>close</button>
</form>
</Modal>
</div>
)
}
}
and this is where the function is being called :
import React from 'react';
import fire from '../config/firebase';
export default class NotesCard extends React.Component {
constructor(props) {
super(props);
this.state = {
editing: false,
note: {}
}
this.handleEditNote = this.handleEditNote.bind(this);
this.handleSaveNote = this.handleSaveNote.bind(this);
}
handleEditNote() {
this.setState({
editing: true
})
}
handleSaveNote(e) {
e.preventDefault()
const userId = fire.auth().currentUser.uid;
const dbRef = fire.database().ref(`users/${userId}/notes/${this.props.note.key}`);
dbRef.update({
title: this.noteTitle.value,
text: this.noteText.value
})
this.setState({
editing: false
})
}
render() {
let editingTemp = (
<span>
<h4>{this.props.note.title}</h4>
<p>{this.props.note.text}</p>
</span>
)
if(this.state.editing) {
editingTemp = (
<form onSubmit={this.handleSaveNote}>
<div>
<input
type='text'
defaultValue={this.props.note.title}
name='title'
ref={ref => this.noteTitle = ref}
/>
</div>
<div>
<input
type='text'
defaultValue={this.props.note.text}
name='text'
ref ={ref => this.noteText = ref}
/>
</div>
<input type='submit' value='done editing' />
</form>
)
}
return (
<div>
<button onClick={this.handleEditNote}>edit</button>
<button onClick={this.props.handleRemoveNote(this.state.note.key)}>delete</button>
{editingTemp}
</div>
)
}
}
Thank you in advance for taking a look at this code.
Second iteration answer
Working sandbox
Problem
looking at https://codesandbox.io/s/trusting-knuth-2og8e?file=/src/components/note-card.js:1621-1708
I see that you have this line
<button onClick={()=> this.props.handleRemoveNote(this.state.note.key)}>delete
Yet your state.note declared as an empty map in the constructor:
this.state = {
editing: false,
note: {}
}
But never assigned a value using this.setState in the component
Solution
Change it to:
<button onClick={()=> this.props.handleRemoveNote(**this.props.note.key**)}>delete</button>
First iteration answer
NotesCard's buttons is firing the onClick callback on render instead on click event.
This is because you have executed the function instead of passing a callback to the onClick handler
Change
<button onClick={this.props.handleRemoveNote(this.state.note.key)}>delete</button>
To
<button onClick={()=> this.props.handleRemoveNote(this.state.note.key)}>delete</button>
I have a input field that I apply a mask to using react-input-mask. I want to change the mask depending on a dropdown value. What is happening is when I change the dropdown value the new mask is applied on the UI but the form value does not get modified. So, when I submit the form the old mask is used. If I modify the value manually in the textbox then the form value change takes affect.
Here is an simplified example:
import React from "react";
import ReactDOM from "react-dom";
import InputMask from "react-input-mask";
import "antd/dist/antd.css";
import { Form, Select } from "antd";
const FormItem = Form.Item;
class FormComponent extends React.Component {
constructor(props) {
super(props);
this.state = { isMaskOne: true };
}
onSelectChange = e => {
if (e === "one") {
this.setState({ isMaskOne: true });
} else {
this.setState({ isMaskOne: false });
}
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form>
<FormItem>
<Select onChange={this.onSelectChange}>
<Select.Option value="one" key="one">
one
</Select.Option>
<Select.Option value="two" key="two">
two
</Select.Option>
</Select>
</FormItem>
<FormItem>
{getFieldDecorator("note")(
<InputMask
mask={this.state.isMaskOne ? "999-99-9999" : "99-9999999"}
maskChar=""
/>
)}
</FormItem>
<p>{JSON.stringify(this.props.form.getFieldValue("note"))}</p>
</Form>
);
}
}
const WrappedFormComponent = Form.create()(FormComponent);
const rootElement = document.getElementById("root");
ReactDOM.render(<WrappedFormComponent />, rootElement);
If the numbers 123-45-6789 are enter into the text box with the dropdown selection of "one" then this.props.form.getFieldValue("note") returns 123-45-6789. When I change the dropdown to "two" I would expect this.props.form.getFieldValue("note") to return 12-3456789 but the value remains 123-45-6789 even though the text has changed to the new mask. What am I not understanding?
You need to use ref to access the input masked value, then you need to update the Form.Item using setFieldsValue i.e. this.props.form.setFieldsValue({ note: this.myRef.current.value });
class FormComponent extends React.Component {
constructor(props) {
super(props);
this.state = { isMaskOne: true };
this.myRef = React.createRef();
}
onSelectChange = e => {
if (e === "one") {
this.setState({ isMaskOne: true }, () => {
console.log("ref value:", this.myRef.current.value);
this.props.form.setFieldsValue({ note: this.myRef.current.value });
});
} else {
this.setState({ isMaskOne: false }, () => {
console.log("ref value:", this.myRef.current.value);
this.props.form.setFieldsValue({ note: this.myRef.current.value });
});
}
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form>
<FormItem>
<Select onChange={this.onSelectChange}>
<Select.Option value="one" key="one">
one
</Select.Option>
<Select.Option value="two" key="two">
two
</Select.Option>
</Select>
</FormItem>
<FormItem style={{ marginTop: "100px" }}>
{getFieldDecorator("note")(
<InputMask
mask={this.state.isMaskOne ? "999-99-9999" : "99-9999999"}
maskChar=""
ref={this.myRef}
/>
)}
</FormItem>
<p>{JSON.stringify(this.props.form.getFieldValue("note"))}</p>
</Form>
);
}
}
It doesn't work correctly, I want to select only one value, but I can select one and more... and can't deselect
there is code for that function.
const RadioButtonField = ({type, options, disabled, onChange}) => {
const handleChange = (value) => {
onChange(type, value);
};
return (
<div>
{options.map(({ value, label }) =>
<Radio.Group key={value}>
<Radio
disabled={disabled}
onChange={() => handleChange(value)}
>
{label}
</Radio>
</Radio.Group>
)}
</div>
);
};
You can try this for single selection and also you can reselect too
import React from "react";
import "./styles.css";
import Radio from "#material-ui/core/Radio";
export default class App extends React.Component {
state = {
selectedValue: null,
radioOptions: [
{ id: 1, title: "1" },
{ id: 2, title: "2" },
{ id: 3, title: "3" },
{ id: 4, title: "4" }
]
};
handleChange = id => {
this.setState({
selectedValue: id
});
};
render() {
const { selectedValue, radioOptions } = this.state;
return (
<div className="App">
{radioOptions.map(option => {
return (
<div className="radio-parent">
<lable
onClick={() => this.handleChange(option.id)}
className="radio-btn"
>
<Radio
color="default"
value={option.id}
name="radioValue"
checked={selectedValue == option.id}
/>
{option.title}
</lable>
</div>
);
})}
</div>
);
}
}
codesandBox link for Demo
You can refer to the following code:
class App extends React.Component {
state = {
initialValue: "A",
options: ["A", "B", "C", "D"]
};
onChange = e => {
console.log("radio checked", e.target.value);
this.setState({
value: e.target.value
});
};
render() {
return (
<Radio.Group value={this.state.initialValue}>
{this.state.options.map((value, index) => {
return (
<Radio onChange={this.onChange} key={index} value={value}>
{" "}
{value}{" "}
</Radio>
);
})}
</Radio.Group>
);
}
}
Working codesandbox demo
I think you do not need to pass anything to the function. Whenever the option will be clicked, the event (e) object will be passed to onChange(e) and you will get the value of clicked item and checked value in onChange(e) e.target.value and e.target.checked respectively.
I'm currently working on my React with REdux application for ASP.NET Core using the Kendo React UI from Telerik. I'm using their grid widget, which, seems to be working ok until you try to edit one of the rows. When you try to edit a row you get the following error:
Warning: Failed prop type: Invalid prop value of type String
supplied to DatePicker, expected instance of Date.
in DatePicker
I searched for an answer to this problem and found a couple of possibilities.
The first was to set the default value defaultValue to null which didn't work.
The second answer suggested setting the format to null i.e. format={null} but that didn't work either.
Here is my code.
ContactContainer
import * as React from 'react';
import { GridColumn, Grid } from '#progress/kendo-react-grid';
import { withState } from './ContactComponent';
import { CommandCell } from './CommandCell';
const ContactsGrid = withState(Grid);
class ContactContainer extends React.Component {
render() {
return (
<div>
<ContactsGrid
sortlable
pageable
pageSize={10}
editField="inEdit">
<GridColumn field="Id" title="Id" editable={false} width={100} />
<GridColumn field="FirstName" title="First Name" />
<GridColumn field="LastName" title="Last Name" />
<GridColumn field="Email" title="Email" />
<GridColumn field="CreatedUser" title="Created By" />
<GridColumn field="CreatedDate" title="Created Date" editor="date" format="{0:d}" defaultValue={null} />
<GridColumn
groupable={false}
sortable={false}
filterable={false}
resizable={false}
field="_command"
title=" "
width="180px"
cell={CommandCell}
/>
</ContactsGrid>
</div>
);
}
}
export default ContactContainer;
ContactComponent
import React from 'react';
import { toDataSourceRequestString, translateDataSourceResultGroups } from '#progress/kendo-data-query';
import { Grid, GridToolbar } from '#progress/kendo-react-grid';
import AddIcon from '#material-ui/icons/Add';
import Fab from '#material-ui/core/Fab';
export function withState() {
return class StatefullGrid extends React.Component {
constructor(props) {
super(props);
if (props.pageable === false) {
this.state = {};
} else {
this.state = {
dataState: {
skip: 0,
take: 20
}
};
}
}
render() {
return (
<Grid
editField="_command"
{...this.props}
{...this.state.dataState}
total={this.state.total}
data={this.state.result}
onItemChange={this.itemChange}
onDataStateChange={this.onDataStateChange}>
<GridToolbar>
<Fab size="small" color="secondary" aria-label="Add" onClick={this.addContact}>
<AddIcon />
</Fab>
</GridToolbar>
{this.props.children}
</Grid>
);
}
componentDidMount() {
this.fetchData(this.state.dataState);
}
addContact = () => {
const data = this.state.result;
data.unshift({ "_command": true, inEdit: true });
this.setState({
result: data
})
};
enterEdit = (item) => {
this.itemInEdit = Object.assign(item, {});
item.inEdit = true;
this.forceUpdate();
};
cancelEdit = (item) => {
let data = this.state.result
let mappedData = data.map(record => {
if (record.Id === this.itemInEdit.Id) {
record = this.itemInEdit;
record.inEdit = false
}
return record
})
this.setState({
result: mappedData
})
};
handleDataStateChange = (changeEvent) => {
this.setState({ dataState: changeEvent.Data });
this.fetchData(changeEvent.data);
};
onDataStateChange = (changeEvent) => {
this.setState({ dataState: changeEvent.Data });
this.fetchData(changeEvent.Data);
};
serialize = (obj) => {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
};
itemChange = (event) => {
switch (event.value) {
case "edit":
this.enterEdit(event.dataItem)
break;
case "delete":
this.deleteItem(event.dataItem)
break;
case "update":
if (event.dataItem.Id) {
this.updateItem(event.dataItem)
} else {
this.addContact(event.dataItem)
}
break;
case "cancel":
this.cancelEdit(event.dataItem)
break;
default:
const data = this.state.result.slice();
const index = data.findIndex(d => d.id === event.dataItem.id);
data[index] = { ...data[index], [event.field]: event.value };
this.setState({
result: data
});
}
};
fetchData(dataState) {
const queryStr = `${toDataSourceRequestString(dataState)}`;
const hasGroups = dataState.group && dataState.group.length;
const base_url = 'api/Contact/GetContacts';
const init = { method: 'GET', accept: 'application/json', headers: {} };
fetch(`${base_url}?${queryStr}`, init)
.then(response => response.json())
.then(({ Data, total }) => {
this.setState({
result: hasGroups ? translateDataSourceResultGroups(Data) : Data,
total,
dataState
});
});
};
}
}
CommandCell
import React from 'react';
import { GridCell } from '#progress/kendo-react-grid';
import IconButton from '#material-ui/core/IconButton';
import Fab from '#material-ui/core/Fab';
import EditIcon from '#material-ui/icons/Edit';
import DeleteIcon from '#material-ui/icons/Delete';
import DoneIcon from '#material-ui/icons/Done';
import CloseIcon from '#material-ui/icons/Close';
export class CommandCell extends GridCell {
buttonClick = (e, command) => {
this.props.onChange({ dataItem: this.props.dataItem, e, field: this.props.field, value: command });
}
render() {
if (this.props.rowType !== "data") {
return null;
}
if (this.props.dataItem.inEdit) {
return (
<td>
<IconButton color="secondary" className="k-grid-save-command"
onClick={(e) => this.buttonClick(e, "update")}>
<DoneIcon />
</IconButton>
<IconButton color="inherit" className="k-grid-cancel-command"
onClick={(e) => this.buttonClick(e, "cancel")}>
<CloseIcon />
</IconButton>
</td>
);
}
return (
<td>
<Fab color="secondary" aria-label="Edit" className="k-grid-edit-command" onClick={(e) => this.buttonClick(e, "edit")}>
<EditIcon />
</Fab>
<Fab color="secondary" aria-label="Delete" className="k-grid-remove-command" onClick={(e) => window.confirm('Confirm deleting: ' + this.props.dataItem.Name) && this.buttonClick(e, "delete")}>
<DeleteIcon />
</Fab>
</td>
);
}
}
Can anyone help me with a solution to this problem or a workaround?
i think problem is here you have assigned defaultValue={null} which throw warning. try passing date in defaultValue
<GridColumn field="CreatedDate" title="Created Date" editor="date" format="{0:d}" defaultValue={new Date()} />
I have a form that dynamically generates inputs, where one input is a material-ui TextField and SelectField with multiple options. I am having a problem with telling the select fields apart from each other though. In an ideal world I would like to be able to collect the data from both of these inputs and store them as an object (i.e. {name: Employee, type_id: 1}), which will become an array of objects depending on how many inputs are generated.
My current code looks like this:
import React from 'react';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import DatatypeStore from '../../stores/DatatypeStore';
const styles = {
customWidth: {
width: 100,
},
};
class MultipleEntry extends React.Component {
state={inputs: [], columnHeaders: [], value: 1};
addInputField(e) {
e.preventDefault();
let inputs = this.state.inputs;
inputs.push({name: null});
this.setState({inputs});
}
handleChange(e, index, value) {
const isSelectField = value !== undefined;
if (isSelectField) {
console.log(index, value);
} else {
console.log(e.target.value);
}
}
render() {
let {inputs, columnHeaders, value} = this.state;
return (
<div className="col-md-12">
{inputs.map((input, index) => {
let name = "header " + index;
return (
<div key={index}>
<br />
<TextField
hintText="Enter the name for the column"
floatingLabelText="Column Name"
type="text"
name={name}
onChange={e => this.handleChange(e)}
/>
<SelectField
value={this.state.value}
onChange={e => this.handleChange(e, index, value)}
style={styles.customWidth}
>
{DatatypeStore.getDatatypes().map(el => {
return <MenuItem key={el.id} value={el.id} primaryText={el.name} />;
})}
</SelectField>
<br />
</div>
);
})}
<br/>
<RaisedButton
style={{marginTop: 50}}
label="Add column input"
secondary={true}
onClick={e => this.addInputField(e)}
/>
<br />
</div>
);
}
}
export default MultipleEntry;
So yeah, examples doing what I would like to do would be much appreciated. If you can do it using material-ui components so much the better!
Thanks for your time
Update
Here is the parent component
import React from 'react';
import MultipleEntry from './MultipleEntry.jsx';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import TokenStore from '../../stores/TokenStore';
const styles = {
paper: {
marginTop: 50,
paddingBottom: 50,
width: '100%',
textAlign: 'center',
display: 'inline-block',
},
};
class ColumnHeaderForm extends React.Component {
state = {title: '', input: null};
changeValue(e) {
const title = e.target.value;
this.setState({
title
});
}
handleInputChange(columnHeaderArray) {
let input = this.state.input;
input = columnHeaderArray;
this.setState({input});
}
handleFormSubmit(e) {
e.preventDefault();
let access_token = TokenStore.getToken();
let title = this.state.title;
let inputs = this.state.input;
this.props.handleFormSubmit(access_token, title, inputs);
}
render() {
let {title, input} = this.state;
return (
<div>
<Paper style={styles.paper}>
<form role="form" autoComplete="off">
<div className="text-center">
<h2 style={{padding: 10}}>Fill out the column names (you can add as many as you need)</h2>
<div className="col-md-12">
<TextField
hintText="Enter a title for the table"
floatingLabelText="Title"
type="text"
onChange={e => this.changeValue(e)}
/>
</div>
<div className="col-md-12">
<MultipleEntry handleInputChange={this.handleInputChange.bind(this)} />
</div>
<RaisedButton
style={{marginTop: 50}}
label="Submit"
primary={true}
onClick={e => this.handleFormSubmit(e)}
/>
</div>
</form>
</Paper>
</div>
);
}
}
export default ColumnHeaderForm;
well from my understanding you want to handle the TextField and SelectField onChange in the same method. They do have different signatures
TextField (event, value)
SelectField (event, index, value)
But you can achieve it easily by testing the third argument for example:
handleChange(event, index, value) {
const isSelectField = value !== undefined;
if(isSelectField) {
// do whatever you need to do with the SelectField value
} else {
// do whatever you need to do with the TextField value
}
}
Note:
You shouldn't mutate your state, that's wrong.
let columnHeaders = this.state.columnHeaders;
columnHeaders[e.target.name] = e.target.value;
To avoid it you can "clone" the state object and apply the changes there..
Object.assign({}, this.state.columnHeaders, {
[e.target.name]: event.target.value
})
Read more about Object.assign here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
----------------------------------------------------
UPDATED EXAMPLE 26/04/2016
Now you can see I'm just changing the typeId inside the input object (that I found by its id) for SelectFields. And almost the same thing for TextField - just change the field name..
handleChange(inputId, event, index, value) {
const isSelectField = value !== undefined;
if(isSelectField) {
this.setState({
inputs: this.state.inputs.map((input) => {
return input.id === inputId ? Object.assign({}, input, {
typeId: value
}) : input
})
})
} else {
this.setState({
inputs: this.state.inputs.map((input) => {
return input.id === inputId ? Object.assign({}, input, {
name: event.target.value
}) : input
})
})
}
}
//Make sure the id is unique for each input
addInputField(e) {
e.preventDefault();
this.setState({
inputs: this.state.inputs.concat({ id: 1, name: null })
});
}
//Binding the ID in the call so we can use it in that method..
<SelectField
value={input.typeId}
onChange={this.handleChange.bind(this, input.id)}
style={styles.customWidth}
>