how I place this.state inside ""? - reactjs

here, I want access to 'this.state.select1' & 'this.state.select2' as factor's object attributes, in the handleClick event handler. how I place these in "", in the way that not become string? because output give me NaN.
This is the desired part of my code:
const factor = {
kilometer: 1,
meter: 1000,
centimeter: 100000,
millimeter: 1000000
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: '',
select1: '',
select2: '',
result: 0
}
}
handleChange1 = (e) => {
this.setState({
text: e.target.value
}
);
}
handleChange2 = (e) => {
this.setState({
select1: e.target.value
}
);
}
handleChange3 = (e) => {
this.setState({
select2: e.target.value
}
);
}
handleClick = () => {
this.setState({
result: (parseInt(this.state.text) * factor['this.state.select1']) /
factor['this.state.select2']
});
}
output:
enter image description here

Related

How do I clear/delete a grocery item in React?

How do I clear/delete a grocery item? I need to make a button that clears a grocery item after I click it. TIA
Here's the code this is for a HW assignment:
class App extends Component {
state = {
grocery: grocery,
item: '',
brand: '',
units: Number,
quantity: Number,
isPurchased: Boolean
}
handleChange = (e) => {
this.setState({ [e.target.id]: e.target.value })
}
handleSubmit = (e) => {
e.preventDefault()
const addGrocery = {
item: this.state.item,
brand: this.state.brand,
units: this.state.units,
quantity: this.state.quantity,
}
this.setState({
grocery: [addGrocery, ...this.state.grocery],
item: '',
brand: '',
units: Number,
quantity: Number,
})
const removeGrocery = {
item: this.state.item
}
}
Here is some codes bro. I fixed something that will give you error in future.
const initialValue = {
grocery: grocery,
item: '',
brand: '',
units: 1,
quantity: 2,
isPurchased: false
}
class App extends Component {
state = initialValue;
handleChange = (e) => {
// added a spread iterator
this.setState({...this.state, [e.target.id]: e.target.value })
}
reset = ()=> {this.setState(initialValue)} // set to initialValue is clearing current state to initial state

React: disable a filtered item

I am creating an activity, where a user needs to match two words on click. Like on the picture below.
If words match they should get disabled.
My state is following
this.state = {
data: [],
mixedWords: [],
myanswers: [],
allPairs: [],
checked: false,
isCorrect: false,
isIncorrect: false
};
For example myanswers array maybe like this.
["more than", "более"]
mixedWords array is the following
[{translation: "more than", disabled: false},
{translation: "capital", disabled: false},
{word: "более", disabled: false},
{translation: "famous", disabled: false},
{word: "проживает", disabled: false},
{translation: "is living", disabled: false},
{word: "известный", disabled: false},
{word: "столице", disabled: false}
]
This function is responsible for modifying disabled property. But the problem is that it outputs only filtered items. How can I output mixedWords array with modifyed disabled property for specific items
const myFunction = (value) => {
const mixedWords = [...this.state.mixedWords]
const result = mixedWords.filter(word => word.translation === value || word.word === value );
const newResult = Object.assign({}, result[0], { disabled:true })
this.setState({
mixedWords:[newResult]
})
}
this.state.myanswers.forEach(myFunction)
Full code
/* eslint-disable no-extend-native */
import React, { Component } from "react";
//import click from "../data/media/click.wav";
//import correct from "../data/media/correct.wav";
//import denied from "../data/media/denied.mp3";
let _ = require("lodash");
class Quiz extends Component {
constructor (props) {
super(props);
this.state = {
data: [],
mixedWords: [],
myanswers: [],
allPairs: [],
checked: false,
isCorrect: false,
isIncorrect: false
};
}
componentDidMount() {
let mixedWords = [];
let allPairs = [];
this.props.data.quiz && this.props.data.quiz.map((item) => {
mixedWords.push({word:item.word, disabled:false},{ translation:item.translation,disabled:false});
allPairs.push(item.pair);
return (mixedWords, allPairs);
});
this.setState({
data: this.props.data.quiz,
mixedWords: _.shuffle(mixedWords),
allPairs
});
//console.log(this.props.data);
}
selectWords = (e) => {
let items = e.target.value;
let myanswers = this.state.myanswers.concat(items);
this.setState({ myanswers }, () => {
if (this.state.myanswers.length === 2) {
if (this.checkAnswers(this.state.myanswers, this.state.allPairs)) {
console.log("correct");
const myFunction = (value) => {
const mixedWords = [...this.state.mixedWords]
const result = mixedWords.filter(word => word.translation === value || word.word === value );
const newResult = Object.assign({}, result[0], { disabled:true })
this.setState({
mixedWords:[newResult]
})
}
this.state.myanswers.forEach(myFunction)
this.setState({
myanswers:[]
})
} else {
console.log("incorrect");
this.setState({
myanswers:[]
})
}
} else {
console.log('choose a pair');
}
});
};
checkAnswers = (answersArr, allPairs) => {
let bools = []
allPairs.forEach((arr) => {
this.arraysEqual(answersArr, arr);
//console.log(this.arraysEqual(answersArr, arr));
//console.log(arr, this.state.myanswers);
bools.push(this.arraysEqual(answersArr, arr))
});
if (bools.includes(true)) {
return true
}
};
arraysEqual = (a, b) => {
return a.sort().toString() === b.sort().toString()
};
render() {
console.log(this.state.mixedWords);
console.log(this.state.myanswers);
//console.log(this.state.allPairs);
//console.log(this.state.myanswers.join(" ") === this.state.answers.join(" "));
return (
<div>
<div className="tags are-medium">
{ this.state.mixedWords.map((item) => (
<button disabled={item.disabled} value={ item.word || item.translation } onClick={ (e) => { this.selectWords(e); } } className="tag is-warning">{ item.word || item.translation }</button>
)) }
</div>
</div>
);
}
}
export default Quiz;
selectWords = (e) => {
let items = e.target.value;
let myanswers = this.state.myanswers.concat(items);
this.setState({ myanswers }, () => {
if (this.state.myanswers.length === 2) {
if (this.checkAnswers(this.state.myanswers, this.state.allPairs)) {
console.log("correct");
const myFunction = (value) => {
this.setState({
mixedWords:this.state.mixedWords.map(word => word.translation === value || word.word === value ? Object.assign({}, word, { disabled:true }) : word)
})
}
this.state.myanswers.forEach(myFunction)
this.setState({
myanswers:[]
})
} else {
console.log("incorrect");
this.setState({
myanswers:[]
})
}
} else {
console.log('choose a pair');
}
});
};

Decrement and increment quantity with Reactjs

I am newbie to Reactjs and I am making a function to increase and decrease quantity. My code below:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quantity: 1,
show: true,
max:5,
min:0
};
}
IncrementItem = () => {
if(this.state.quantity > 9) {
}else {
this.setState({
quantity: this.state.quantity + 1
});
}
}
DecreaseItem = () => {
if(this.state.quantity <= 1) {
}else {
this.setState({ quantiy: this.state.quantity - 1 });
}
}
ToggleClick = () => {
this.setState({ show: !this.state.show });
}
render() {
return (
<div>
<button onClick={this.IncrementItem}>+</button>
<input className="inputne" value={this.state.quantity} />
<button onClick={this.DecreaseItem}>-</button>
</div>
);
}
I have problems are:
Browser appears an error :
Warning: Failed prop type: You provided a value prop to a form field without an onChange handler
I cannot change value in input from View.
Please let me know how to solve. Thank for your help.
There are two issues in this code:
There is no onChange handler. Read more on how to handle onChange listeners here
Using value from this.state.quantity to increment and decrement is bad practice because setState function is asynchronous.
You can use functional version of setState to get around this:
this.setState(prevState => {
if(prevState.quantity > 0) {
return {
quantity: prevState.quantity - 1
}
} else {
return null;
}
});
Code Snippet:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quantity: 1,
show: true,
max: 5,
min: 0
};
}
IncrementItem = () => {
this.setState(prevState => {
if(prevState.quantity < 9) {
return {
quantity: prevState.quantity + 1
}
} else {
return null;
}
});
}
DecreaseItem = () => {
this.setState(prevState => {
if(prevState.quantity > 0) {
return {
quantity: prevState.quantity - 1
}
} else {
return null;
}
});
}
ToggleClick = () => {
this.setState({
show: !this.state.show
});
}
handleChange = (event) => {
this.setState({quantity: event.target.value});
}
render() {
return ( <div>
<button onClick={this.IncrementItem}>+</button>
<input className="inputne" value={this.state.quantity} onChange={this.handleChange}/>
<button onClick = {this.DecreaseItem}>-< /button>
</div>
);
}
}
ReactDOM.render( < App / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
You need to Update the value, add a onChange on Input field to do that.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quantity: 1,
show: true,
max:5,
min:0
};
}
IncrementItem = () => {
if(this.state.quantity > 9) {
}else {
this.setState({
quantity: this.state.quantity + 1
});
}
}
DecreaseItem = () => {
if(this.state.quantity <= 1) {
}else {
this.setState({ clicks: this.state.quantity - 1 });
}
}
ToggleClick = () => {
this.setState({ show: !this.state.show });
}
UpdateValue = (e) => {
this.setState({ quantity: e.target.value });
}
render() {
return (
<div>
<button onClick={this.IncrementItem}>+</button>
<input className="inputne" value={this.state.quantity} onChange={this.UpdateValue} />
<button onClick={this.DecreaseItem}>-</button>
</div>
);
}
Try this as well it may help you
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 4, max: 15, min: 0, show: true },
{ id: 2, value: 0 }`enter code here`
]
};
handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
if (counters[index].value < counters[index].max) {
counters[index].value++;
}
this.setState({ counters });
};
handleDecrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
if (counters[index].value > counters[index].min) {
counters[index].value--;
}
this.setState({ counters });
};
handleDelete = counterId => {
const counters = this.state.counters.filter(c => c.id !== counterId);
this.setState({ counters });
};
render() {
return (
<div>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onDelete={this.handleDelete}
onIncrement={this.handleIncrement}
onDecrement={this.handleDecrement}
counter={counter}
/>
))}
</div>
);
}
}
export default Counters;
enter code here

Unable to update form field in react via prevState

I have a state variable as:
constructor(props) {
super(props)
this.state = {
fields: {
applicantName: '',
applicantType: '',
applicantAddress: '',
applicantContact: '',
buildingName: '',
buildingAddress: '',
area:'',
}
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
and I have a function :
handleChange(event) {
this.setState((prevState) => {
fields: {
...prevState.fields, //Unexpected token ..
{
event.target.name: event.target.value,
},
}
});
}
How I am not able to see any type of syntax here...but my module build fails and it says syntax error near '...'
you need return Object
handleChange(event) {
// note here => ({
this.setState((prevSate) => ({
fields: {
...prevState.fields,
//and there ..
[event.target.name]: event.target.value
})
});
}
UPDATE
Based on Abdullah suggestion, its better when you use ...prevState for wohle state:
handleChange(event) {
// note here => ({
this.setState((prevSate) => ({
// note change here
...prevState,
fields: {
...prevState.fields,
//and there ..
[event.target.name]: event.target.value
})
});
}
UPDATE 2
based on PraveenRaoChavan comment:
typo fix:
need use event not e
handleChange(event) {
this.setState(prevState => ({
fields: {
...prevState.fields,
{
event.target.name: e.target.value,
},
}
}));
}
You have a typo in there
change
this.setState((prevSate) => { }
to
this.setState((prevState) => { }

How to add an object from text input into an array in react native?

I have an array of objects like this:
const data = {
0: {
isEditing:false,
text: 'Chloe',
},
1: {
isEditing:false,
text: 'Jasper',
},
2: {
isEditing:false,
text: 'Pepper',
}};
I want to create an add method for this but I have no clue how to insert the item at the next index. I can't change the structure of array because I need to use the sortable-list library for drag and drop.
Here's my code:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: "",
db: []
};
this.textChange = this.textChange.bind(this);
this.addTask = this.addTask.bind(this);
}
textChange = value => {
const inputValue = value;
this.setState(() => ({
inputValue
}));
};
addTask = () => {
if (!this.state.inputValue) {
return;
}
//this.state.db.push({
// isEditing:false,
// text: this.state.inputValue
// });
data.index = {
isEditing:false,
text: this.state.inputValue
}
index++;
this.setState({
...this.state,
data:this.state.data,
inputValue: ""
});
// rowsState - array: {text, isEditing}
};
}
I manage to find the answer.
addTask = () => {
if (!this.state.inputValue) {
return;
}
let newData = {};
let l = Object.keys(this.state.data).length;
console.log("l=", l);
let i = 0;
for (i = 0; i < l; i++) {
let el = this.state.data[i]; // i + ""
newData[i] = el;
}
newData[l] = { text: this.state.inputValue, isEditing: false };
this.setState({
...this.state,
data: newData,
inputValue: ""
});
};

Resources