How to create an array based on multiple inputs - javascript

I am trying create an array with some objects in it, Im trying to gather the data from multiple inputs. I am creating a restaurant Menu, where I will have different titles such as Breakfasts, Entrees... and under each title I will have different plates.
Im trying to create an array like this:
menu: [
[ 'Lunch',
[{plate: 'Rice and Beans', description: 'Rice and Beans for Lunch', price: 50.49 }]
]
[ 'Dinner',
[{plate: 'Some Dinner', description: 'Dinner Description', price: 35.49 }]
]
]
The question is, how do I add first a Title, and under that title how do I add plates?

I also wanted to know how to make it, so I made it for practice. I hope it helps.
import React from 'react';
class MenuInput extends React.Component {
render() {
const {id, handleInput} = this.props;
return (
<div>
Title : <input name="title" onChange={(e) => handleInput(id, e)}/>
Plate : <input name="plate" onChange={(e) => handleInput(id, e)}/>
Description : <input name="description" onChange={(e) => handleInput(id, e)}/>
Price : <input name="price" onChange={(e) => handleInput(id, e)}/>
</div>
)
}
}
export default class Menu extends React.Component {
state = {
inputCount: 1,
inputData: [[]],
result: []
}
saveData = (e) => {
const {inputData, result} = this.state;
inputData.forEach(input => {
const {title, plate, description, price} = input;
const findInputIndex = result.findIndex(data => data.indexOf(title) >= 0);
if (findInputIndex >= 0) {
const [menuName, menuList] = result[findInputIndex];
result[findInputIndex] = [menuName, [...menuList, {plate, description, price}]]
} else {
result.push([title, [{plate, description, price}]])
}
});
this.setState({
result
})
}
handleInput = (id, e) => {
const {name, value} = e.target;
const {inputData} = this.state;
inputData[id] = {...inputData[id], [name]: value};
this.setState({
inputData
})
}
addInput = () => {
const {inputCount, inputData} = this.state;
this.setState({
inputCount: inputCount + 1,
inputData: [...inputData, []]
})
};
getInputList = () => {
const {inputCount} = this.state;
let inputList = [];
for (let i = 0; i < inputCount; i++) {
inputList.push(<MenuInput id={i} key={i} handleInput={this.handleInput}/>)
}
return inputList
}
render() {
const {result} = this.state;
console.log(result)
return (
<div>
{this.getInputList()}
<button onClick={this.addInput}>Add Plate</button>
<br/>
<button onClick={this.saveData}>save</button>
{
result.length > 0 && result.map(res => {
const [menuName, menuList] = res;
return (
<div key={menuName}>
<strong>Title : {menuName}</strong>
{menuList.map(menu => {
const {plate, description, price} = menu;
return(
<div key={plate}>
<span style={{marginRight : '10px'}}>plate : {plate}</span>
<span style={{marginRight : '10px'}}>description : {description}</span>
<span>price : {price}</span>
</div>
)
})}
</div>
)
})
}
</div>
)
}
}

Related

How to filter by ingredients on React

Currently I can filter by 1 ingredient, but when i try to select multiple ingredients (checkboxes), My recipes disappear as "ingredient1, ingredient2" is being passed to my searchfield rather than ingredient 1 & ingredient2.
My code for my search/filter is
import React, { useState } from "react";
import DisplayFoodItems from "./DisplayFoodItems";
import { ingredients } from "../data/Ingredients";
function Search({ details }) {
const [searchField, setSearchField] = useState("");
const [checked, setChecked] = useState([]);
const all = [...checked];
const filtered = details.filter((entry) => {
//Search box
if (entry.name.toLowerCase().includes(searchField.toLowerCase()) ||
entry.catagory.toLowerCase().includes(searchField.toLocaleLowerCase())) {
return (
entry.name.toLowerCase().includes(searchField.toLowerCase()) ||
entry.catagory.toLowerCase().includes(searchField.toLocaleLowerCase())
)
}
//Filter checkboxes
for (var i = 0; i < entry.ingredients.length; i++) {
console.log(searchField)
if (entry.ingredients[i].toLowerCase().includes(searchField.toLocaleLowerCase())) {
return (
entry.ingredients[i].toLowerCase().includes(searchField.toLocaleLowerCase())
);
}
}
}
);
const handleToggle = c => () => {
// return the first index or -1
const clickedBox = checked.indexOf(c);
if (clickedBox === -1) {
all.push(c);
console.log(all)
setSearchField(all.toString())
} else {
all.splice(clickedBox, 1);
setSearchField("")
}
console.log(all);
setChecked(all);
};
return (
<>
<div>
<input id="search"
className="form-control"
type="text"
placeholder="Search by recipe name or catagory"
onChange={(e) => setSearchField(e.target.value)}
/>
</div>
<div>
{ingredients.map((ingredient, index) => (
<label key={index} className="form-check-label">
<input
onChange={handleToggle(ingredient.name)}
type="checkbox"
className="mr-2"
/>
{ingredient.name}</label>
))}
<hr></hr>
</div>
<div class="flex">
<DisplayFoodItems foodList={filtered} />
</div>
</>
);
}
export default Search;
Here is a picture of my screen if it helps at all
All checkboxes work individually but for example, if salt and oil when checked together it should return Bacon wrapped chicken and Smashed potatoes, however it returns blank at present.
I have tried looping the all array and sending that to setSearchField, but again, I cannot get it to work.
I have tried looping through the array of checked ingredients and sending that to the setSearchField. Im expecting recipes to appear if they contain an ingredient that has been checked.
If I understand correctly you want something like this?
const foodList = [
{ name: "Food 1", ingredients: ["Salt"] },
{ name: "Food 2", ingredients: ["Oil"] },
{ name: "Food 3", ingredients: ["Milk"] },
{ name: "Food 4", ingredients: ["Salt", "Oil"] },
{ name: "Food 5", ingredients: ["Oil", "Milk"] },
{ name: "Food 6", ingredients: ["Oil", "Salt", "Milk"] },
];
const ingredientList = ["Salt", "Oil", "Milk"]
const Example = () => {
const [ingredients, setIngredients] = useState([]);
const filtered = foodList.filter(food => {
return ingredients.length === 0
|| food.ingredients.length > 0 && ingredients.every(selectedIngredient =>
food.ingredients.some(foodIngredient => foodIngredient.toLowerCase() === selectedIngredient.toLowerCase()));
});
return (
<div>
<h2>Filter</h2>
{
ingredientList.map((ingredient, i) => {
const checked = ingredients.some(selectedIngredient => ingredient.toLowerCase() === selectedIngredient.toLowerCase());
return (
<label key={`ingredient-${i}`}>
<input
type="checkbox"
checked={checked}
onChange={() => {
if (checked) {
setIngredients(ingredients.filter(selectedIngredient => ingredient.toLowerCase()!== selectedIngredient.toLowerCase()))
}
else {
setIngredients([...ingredients, ingredient]);
}
}} />
{ingredient}
</label>
);
})
}
<br />
<br />
<h2>Food list</h2>
<pre>{JSON.stringify(filtered, null, 4)}</pre>
</div>
);
}

edit notes on a Google Keep clone app with React js

I am building a clone of the Google Keep app with react js. I added all the basic functionality (expand the create area, add a note, delete it) but I can't seem to manage the edit part. Currently I am able to edit the inputs and store the values in the state, but how can I replace the initial input values for the new values that I type on the input?
This is Note component
export default function Note(props) {
const [editNote, setEditNote] = useState(false);
const [currentNote, setCurrentNote] = useState({
id: props.id,
editTitle: props.title,
editContent: props.content,
});
const handleDelete = () => {
props.deleteNote(props.id);
};
const handleEdit = () => {
setEditNote(true);
setCurrentNote((prevValue) => ({ ...prevValue }));
};
const handleInputEdit = (event) => {
const { name, value } = event.target;
setCurrentNote((prevValue) => ({
...prevValue,
[name]: value,
}));
};
const updateNote = () => {
setCurrentNote((prevValue, id) => {
if (currentNote.id === id) {
props.title = currentNote.editTitle;
props.content = currentNote.editContent;
} else {
return { ...prevValue };
}
});
setEditNote(false);
};
return (
<div>
{editNote ? (
<div className='note'>
<input
type='text'
name='edittitle'
defaultValue={currentNote.editTitle}
onChange={handleInputEdit}
className='edit-input'
/>
<textarea
name='editcontent'
defaultValue={currentNote.editContent}
row='1'
onChange={handleInputEdit}
className='edit-input'
/>
<button onClick={() => setEditNote(false)}>Cancel</button>
<button onClick={updateNote}>Save</button>
</div>
) : (
<div className='note' onDoubleClick={handleEdit}>
<h1>{props.title}</h1>
<p>{props.content}</p>
<button onClick={handleDelete}>DELETE</button>
</div>
)}
</div>
);
}
And this is the Container component where I am renderind the CreateArea and mapping the notes I create. I tried to map the notes again with the new values but it wasn't working.
export default function Container() {
const [notes, setNotes] = useState([]);
const addNote = (newNote) => {
setNotes((prevNotes) => {
return [...prevNotes, newNote];
});
};
const deleteNote = (id) => {
setNotes((prevNotes) => {
return prevNotes.filter((note, index) => {
return index !== id;
});
});
};
// const handleUpdateNote = (id, updatedNote) => {
// const updatedItem = notes.map((note, index) => {
// return index === id ? updatedNote : note;
// });
// setNotes(updatedItem);
// };
return (
<div>
<CreateArea addNote={addNote} />
{notes.map((note, index) => {
return (
<Note
key={index}
id={index}
title={note.title}
content={note.content}
deleteNote={deleteNote}
//handleUpdateNote={handleUpdateNote}
/>
);
})}
</div>
);
}
There are a couple of mistakes in your code.
The state properties are in the camel case
const [currentNote, setCurrentNote] = useState({
...
editTitle: props.title,
editContent: props.content,
});
But the names of the input are in lowercase.
<input
name='edittitle'
...
/>
<textarea
name='editcontent'
...
/>
Thus in handleInputEdit you don't update the state but add new properties: edittitle and editcontent. Change the names to the camel case.
In React you cant assign to the component prop values, they are read-only.
const updateNote = () => {
...
props.title = currentNote.editTitle;
props.content = currentNote.editContent;
You need to use the handleUpdateNote function passed by the parent component instead. You have it commented for some reason.
<Note
...
//handleUpdateNote={handleUpdateNote}
/>
Check the code below. I think it does what you need.
function Note({ id, title, content, handleUpdateNote, deleteNote }) {
const [editNote, setEditNote] = React.useState(false);
const [currentNote, setCurrentNote] = React.useState({
id,
editTitle: title,
editContent: content,
});
const handleDelete = () => {
deleteNote(id);
};
const handleEdit = () => {
setEditNote(true);
setCurrentNote((prevValue) => ({ ...prevValue }));
};
const handleInputEdit = (event) => {
const { name, value } = event.target;
setCurrentNote((prevValue) => ({
...prevValue,
[name]: value,
}));
};
const updateNote = () => {
handleUpdateNote({
id: currentNote.id,
title: currentNote.editTitle,
content: currentNote.editContent
});
setEditNote(false);
};
return (
<div>
{editNote ? (
<div className='note'>
<input
type='text'
name='editTitle'
defaultValue={currentNote.editTitle}
onChange={handleInputEdit}
className='edit-input'
/>
<textarea
name='editContent'
defaultValue={currentNote.editContent}
row='1'
onChange={handleInputEdit}
className='edit-input'
/>
<button onClick={() => setEditNote(false)}>Cancel</button>
<button onClick={updateNote}>Save</button>
</div>
) : (
<div className='note' onDoubleClick={handleEdit}>
<h1>{title}</h1>
<p>{content}</p>
<button onClick={handleDelete}>DELETE</button>
</div>
)}
</div>
);
}
function CreateArea() {
return null;
}
function Container() {
const [notes, setNotes] = React.useState([
{ title: 'Words', content: 'hello, bye' },
{ title: 'Food', content: 'milk, cheese' }
]);
const addNote = (newNote) => {
setNotes((prevNotes) => {
return [...prevNotes, newNote];
});
};
const deleteNote = (id) => {
setNotes((prevNotes) => {
return prevNotes.filter((note, index) => {
return index !== id;
});
});
};
const handleUpdateNote = ({ id, title, content }) => {
const _notes = [];
for (let i = 0; i < notes.length; i++) {
if (i === id) {
_notes.push({ id, title, content });
} else {
_notes.push(notes[i]);
}
}
setNotes(_notes);
};
return (
<div>
<CreateArea addNote={addNote} />
{notes.map((note, index) => {
return (
<Note
key={index}
id={index}
title={note.title}
content={note.content}
deleteNote={deleteNote}
handleUpdateNote={handleUpdateNote}
/>
);
})}
</div>
);
}
function App() {
return (
<div>
<Container />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
Also, you can store the notes in an object or hash map instead of an array. For example
const [notes, setNotes] = React.useState({
'unique_id': { title: 'Words', content: 'hello, bye' }
});
Then in handleUpdateNote you have
setNotes((prev) => ({ ...prev, unique_id: { title, content } }))

Conditionally disable React Checkbox

I am trying to conditionally disable the checkbox in react, based on the count. Passing the value through props whether it is checked and greater than the number. I am saving the name in the state to further process it to send to in the backend database.
Here is my react code.
class CheckboxComponent extends Component {
constructor(props) {
super(props);
this.state = {
checkedItems: {}
};
}
handleChange = (event, formKey) => {
const {checkedItems} = this.state;
const checkedValues = {...checkedItems};
checkedValues[event.target.name] = event.target.checked;
this.setState((prevState, currState) => {
return {
...prevState,
checkedItems: checkedValues
}
});
};
render = () => {
const {checkedItems} = this.state;
const checkedValues = {...checkedItems};
const checkedCount = Object.values(checkedValues).length;
const checked = Object.values(checkedValues);
const disabled = checkedCount >= 3;
return (
<div>
{checkboxes.map((item, index) => (
<label className={`form__field__input__label`} key={item.key}>
<Input
type={`checkbox`}
name={item.name}
checked={this.state.checkedItems[item.name] || false}
onChange={this.handleChange}
formKey={'subjects'}
disabled={(!checked[index] && checked.length > 3)}
/>
{item.name}
</label>
))}
</div>
)
This is the Array that I am passing to render the values in the checkbox
const checkboxes = [
{
name: "Math and economics",
key: "mathsandeconomics",
label: "Math and economics"
},
{
name: "Science",
key: "Science",
label: "Science"
},
The below code snippet will work fine for you. And you can sent object to the backend having maximum of only 3 properties set to true. Get the full code from codesandbox link https://codesandbox.io/s/emmeiwhite-0i8yh
import React from "react";
const checkboxes = [
{
name: "Math and economics",
key: "mathsandeconomics",
label: "Math and economics",
},
{
name: "Science",
key: "science",
label: "Science",
},
{
name: "history",
key: "history",
label: "history",
},
{
name: "literature",
key: "literature",
label: "literature",
},
];
class CheckboxComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
checkedItems: {},
count: 0,
};
}
handleChange = (event, formKey) => {
const { name, checked } = event.target;
const updatedCheckedItems = { ...this.state.checkedItems, [name]: checked };
this.setState({
checkedItems: updatedCheckedItems,
count: Object.values(updatedCheckedItems).filter((value) => value).length,
});
};
render = () => {
const checkedValues = { ...this.state.checkedItems };
const checkedCount = Object.values(checkedValues).filter((value) => value)
.length;
console.log(this.state.checkedItems);
return (
<div>
{checkboxes.map((item, index) => (
<label className={`form__field__input__label`} key={item.key}>
<input
type={`checkbox`}
name={item.name}
checked={this.state.checkedItems[item.name] || false}
onChange={this.handleChange}
disabled={!checkedValues[item.name] && checkedCount > 2}
/>
{item.name}
</label>
))}
</div>
);
};
}
export default CheckboxComponent;
Your checked.length counts all touched boxes, not checked only. If you uncheck an input, it still will be counted. Count only true, for example Object.values(checkedValues).filter(value => value).length.
Use names instead of indexes: disabled={!checkedValues[item.name] && checkedCount > 3}
You can see full solution here: https://codesandbox.io/s/confident-http-vlm04?file=/src/App.js
event.target.getAttribute('name');
try this to get name attribute, pretty sure event.target.name is 'undefined'
I see one use case is not taken care of. checkedCount should count the number of true values only.
const checkedCount = Object.values(checkedValues).length; // existing
const checkedCount = Object.values(checkedValues).filter(item=>item==true).length //replace with this line
This would solve the problem.
Here is the code and as well as codesandbox link
Codesandbox Link
import React from "react";
export class CheckboxComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
checkedItems: {},
checkedCount: 0
};
}
handleChange = (event, formKey) => {
const { checkedItems } = this.state;
const checkedValues = { ...checkedItems };
checkedValues[event.target.name] = event.target.checked;
this.setState((prevState, currState) => {
return {
...prevState,
checkedItems: checkedValues,
checkedCount: event.target.checked
? prevState.checkedCount + 1
: prevState.checkedCount - 1
};
});
};
render = () => {
const { checkboxes } = this.props;
const { checkedCount } = this.state;
const disabled = checkedCount >= 3;
return (
<div>
<p></p>
{checkboxes.map((item, index) => (
<label className={`form__field__input__label`} key={item.key}>
<input
type={`checkbox`}
name={item.name}
checked={this.state.checkedItems[item.name] || false}
onChange={this.handleChange}
disabled={!this.state.checkedItems[item.name] ? disabled : false}
/>
{item.name}
</label>
))}
</div>
);
};
}

React doesn't render form autofill suggestions

I'm using react to create a panel to add a new product. I've created a separate auto-complete class which is supposed to render an input element and a list of suggested autofill items underneath. The input element shows but not the autofill suggestions. Have a look at the code
Autofill class
import React, { Component } from "react";
import firebase from "../Firebase";
export default class AutoCompleteDistID extends Component {
constructor() {
super();
this.state = {
sellerName: [],
sellerId: [],
suggestions: [],
};
}
componentDidMount() {
var sellerRef = firebase.database().ref().child("Sellers");
sellerRef.once("value", (snapshot) => {
snapshot.forEach((childSnap) => {
var distrName = childSnap.val().sellerName;
var distrId = childSnap.val().sellerName.sellerId;
// var distrName = [{ name: data.sellerName }];
this.setState((prevState) => {
return {
sellerName: [...prevState.sellerName, distrName],
sellerId: [...prevState.sellerId, distrId],
suggestions: [...prevState.suggestions, distrName],
};
});
});
});
}
onTextChange = (e) => {
var sellerNames = [this.state.sellerName];
const value = e.target.value;
let newSuggestions = [];
if (value.length > 0) {
const regex = new RegExp(`^${value}`, "i");
newSuggestions = sellerNames.sort().filter((v) => regex.test(v));
}
this.setState(() => ({ newSuggestions }));
};
renderSuggestions() {
const newSuggestions = this.state.suggestions;
if (newSuggestions.length === 0) {
return null;
}
return (
<ul>
{newSuggestions.map((item) => (
<li>{item}</li>
))}
</ul>
);
}
render() {
return (
<div>
<input onChange={this.onTextChange} />
{this.renderSuggestions}
</div>
);
}
}
Main form
import React, { Component } from "react";
import firebase from "../Firebase";
import AutoCompleteDistID from "./AutoCompleteDistID";
export default class Products extends Component {
constructor() {
super();
this.state = {
description: "",
prodQty: "",
};
this.pushProduct = this.pushProduct.bind(this);
}
handleFormChange = (event) => {
const target = event.target;
const colName = target.name;
this.setState({
[colName]: event.target.value,
});
};
pushProduct() {
const userRef = firebase.database().ref().child("Users"); //Get reference to Users DB
const prodData = this.state;
userRef.push(prodData);
}
render() {
return (
<div>
<br />
<form style={{ border: "solid", borderWidth: "1px", width: "600px" }}>
<br />
<input
type="text"
value={this.state.prodQty}
placeholder="Available Quantity"
onChange={this.handleFormChange}
name="prodQty"
/>
<input
type="text"
value={this.state.description}
placeholder="Description"
onChange={this.handleFormChange}
name="description"
/>
<AutoCompleteDistID />
<br />
<br />
</form>
<button onClick={this.pushProduct} type="button">
Add Product
</button>
<br />
</div>
);
}
}
State variable is suggestions but you are setting newSuggestions.
onTextChange = (e) => {
var sellerNames = [this.state.sellerName];
const value = e.target.value;
let newSuggestions = [];
if (value.length > 0) {
const regex = new RegExp(`^${value}`, "i");
newSuggestions = sellerNames.sort().filter((v) => regex.test(v));
}
// HERE IS THE MISTAKE
this.setState(() => ({ suggestions: newSuggestions }));
};
In AutoCompleteDistID render method
render() {
return (
<div>
<input onChange={this.onTextChange} />
{this.renderSuggestions()}
</div>
);
}

Boolean checkbox value in JSX doesn't work

IU'm using a github code example and that works perfectly with text inputs & numbers, but when I want to use checkbox inputs, the application doesn't understand the values and returns null or just on values...
Any idea why this doesn't work on fEdit function?
import React, { Component } from "react";
// import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
title: "React Simple CRUD Application",
act: 0,
index: "",
datas: []
};
}
componentDidMount() {
this.refs.name.focus();
}
handleChange = e => {
console.log(e.target.value);
};
fSubmit = e => {
e.preventDefault();
console.log("try");
let datas = this.state.datas;
let name = this.refs.name.value;
let isenable = this.refs.isenable.value;
if (this.state.act === 0) {
//new
let data = {
name,
isenable
};
datas.push(data);
console.log(data.isenable);
} else {
//update
let index = this.state.index;
datas[index].name = name;
datas[index].isenable = isenable;
}
this.setState({
datas: datas,
act: 0
});
this.refs.myForm.reset();
this.refs.name.focus();
};
fRemove = i => {
let datas = this.state.datas;
datas.splice(i, 1);
this.setState({
datas: datas
});
this.refs.myForm.reset();
this.refs.name.focus();
};
fEdit = i => {
let data = this.state.datas[i];
this.refs.name.value = data.name;
this.refs.isenable.value = data.isenable;
this.setState({
act: 1,
index: i
});
this.refs.name.focus();
};
render() {
let datas = this.state.datas;
return (
<div className="App">
<h2>{this.state.title}</h2>
<form ref="myForm" className="myForm">
<input
type="text"
ref="name"
placeholder="your name"
className="formField"
/>
<input
type="checkbox"
ref="isenable"
placeholder="your isenable"
className="formField"
/>
<button onClick={e => this.fSubmit(e)} className="myButton">
submit
</button>
</form>
<pre>
{datas.map((data, i) => (
<li key={i} className="myList">
{data.name} - {(data.isenable || false).toString()}
<button onClick={() => this.fRemove(i)} className="myListButton">
remove
</button>
<button onClick={() => this.fEdit(i)} className="myListButton">
edit
</button>
</li>
))}
</pre>
</div>
);
}
}
export default App;
When working with checkboxes, refer to the checked property not the value. This is the true or false state of the checkbox.
In fSubmit:
let isenable = this.refs.isenable.checked;
In fEdit:
this.refs.isenable.checked = data.isenable;
In the render:
{data.name} - {data.isenable ? 'on' : 'off'}
Working demo
Complete code with fixes:
class App extends Component {
constructor(props) {
super(props);
this.state = {
title: "React Simple CRUD Application",
act: 0,
index: "",
datas: []
};
}
componentDidMount() {
this.refs.name.focus();
}
handleChange = e => {
console.log(e.target.value);
};
fSubmit = e => {
e.preventDefault();
console.log("try");
let datas = this.state.datas;
let name = this.refs.name.value;
let isenable = this.refs.isenable.checked;
if (this.state.act === 0) {
//new
let data = {
name,
isenable
};
datas.push(data);
console.log(data.isenable);
} else {
//update
let index = this.state.index;
datas[index].name = name;
datas[index].isenable = isenable;
}
this.setState({
datas: datas,
act: 0
});
this.refs.myForm.reset();
this.refs.name.focus();
};
fRemove = i => {
let datas = this.state.datas;
datas.splice(i, 1);
this.setState({
datas: datas
});
this.refs.myForm.reset();
this.refs.name.focus();
};
fEdit = i => {
let data = this.state.datas[i];
this.refs.name.value = data.name;
this.refs.isenable.checked = data.isenable;
this.setState({
act: 1,
index: i
});
this.refs.name.focus();
};
render() {
let datas = this.state.datas;
return (
<div className="App">
<h2>{this.state.title}</h2>
<form ref="myForm" className="myForm">
<input
type="text"
ref="name"
placeholder="your name"
className="formField"
/>
<input
type="checkbox"
ref="isenable"
placeholder="your isenable"
className="formField"
/>
<button onClick={e => this.fSubmit(e)} className="myButton">
submit
</button>
</form>
<pre>
{datas.map((data, i) => (
<li key={i} className="myList">
{data.name} - {data.isenable ? 'on' : 'off'}
<button onClick={() => this.fRemove(i)} className="myListButton">
remove
</button>
<button onClick={() => this.fEdit(i)} className="myListButton">
edit
</button>
</li>
))}
</pre>
</div>
);
}
}
Sidenote: I wouldn't use Refs in this case. Take a look at the docs, you can see when to use Refs and when not to. The Forms docs cover how to handle forms without Refs.
You should use the checked attribute of the isenable element to determine whether the checkbox is checked and put this value in your form. You can check the mdn docs: https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/checkbox

Categories