How can I use functional update with event.currentTarget.value in React?
First, please check my code.
const [name, setName] = useState('nick');
const handleChangeName = (e) => {
setName(prevState => e.currentTarget.value)
}
return (
<input value={name} onChange={handleChangeName} />
)
I'm trying to do functional update not
setName(e.currentTarget.value)
However, with this code,
const handleChangeName = (e) => {
setName(prevState => e.currentTarget.value)
}
I am not getting the right value for some reason. If you know what is the problem or the answer, please let me know! Thank you.
1 answer
-
answered 2022-05-07 06:09
Khalfoun Mohamed El Mehdi
use target instead of currentTarget
const handleChangeName = (e) => { setName(prevState => e.target.value) }
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
react-router-dom v6 params only numbers
I want add number regex in may param in react-router-dom v6. it work fin in v5 like it:
<Route path="list/:id(\d+)" element={<MyComponent/>} />
but it not work in v6.
-
How can I fixed my problem"FirebaseError: Firebase: Error (auth/invalid-api-key)."
My environment variable is ok. No comas and name mistakes but they given me error like "FirebaseError: Firebase: Error (auth/invalid-api-key)". How can I fixed it. Please Help me...
This my .env file
REACT_APP_apiKey=AIzaSyBWobnhbdeMdNpXXXXXXXXXXXXXXXXXXXX REACT_APP_authDomain=XXXXX.firebaseapp.com REACT_APP_projectId=XXXX REACT_APP_storageBucket=XXXXX.appspot.com REACT_APP_messagingSenderId=4997390XXXXX REACT_APP_appId=1:4997390XXXXX:web:cc7bc80aa1bdb78fXXXXXX REACT_APP_measurementId=G-M1XDXXXXXX
This my firebase config file
const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId: process.env.REACT_APP_measurementId, }; when I debugging firebaseConfig object console.log(firebaseConfig.apiKey); ==========> undefined console.log(firebaseConfig.authDomain); ==========> undefined console.log(firebaseConfig.projectId); ==========> undefined console.log(firebaseConfig.storageBucket); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined console.log(firebaseConfig.appId); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined
client side given error this "FirebaseError: Firebase: Error (auth/invalid-api-key)"
-
How to get pass an array through a function with a user input?
I want to ask the user for the size of a 2D array arr[][], but also pass it through the function initializeArray. However, if I pass it through the function, I would have to have a size declarator for col, which doesn't allow the user to enter their own value for the size
#include<iostream> using namespace std; void initializeArray(arr[][10], int N); int main() { int N; cout << "enter an array size: "; cin >> N; int arr[N][N]; initializeArray(arr, N); // I get an error here for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) cout << arr[i][j] << " "; cout << endl; } } void initializeArray(int arr[][10], int N) { for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) arr[i][j] = 0; }
The only solution I found was the make arr[][] a global array, but in that case, I would have to still declare the size parameters, and I want the user to enter whatever they want. Is there another way to fix this?
-
Two-dimensional array C++
Problem: Write a program of a two dimensional integer array of exactly four rows and four columns, and find the sum of the integers each row of the array as well as determine the smallest inputted element/data in the array. The user will input the elements. Display the elements in tabular form. Make the program user friendly. Use a Class and a member function for the process involve.
-
Generic Events Emitted from Component in Angular ~13
I'm trying to determine if I'm going down an undesirable path with how I'm approaching generic event management in an Angular application.
The question I have is: Is there a more built-in or best-practices-conforming way to achieve the following.
Given a simple type, representing an item:
export interface Item { name: string; }
I want to create a very generic item list component, that supports emitting actions dictated by the containing component. I've created an
Action
type representing the types of actions that can be emitted, and anActionEvent<TPayload>
type representing the emitted action event:export interface Action { name: string; } export interface ActionEvent<TPayload> { name: string; payload: TPayload; }
The generic item list component is then defined as such:
@Component({ selector: "list-component", template: ` <table> <tbody> <tr *ngFor="let item of this.items"> <td>{{item.name}}</td> <td> <button *ngFor="let action of this.actions" (click)="this.doAction(action.name, item)"> <span>{{action.name}}</span> </button> </td> </tr> </tbody> </table> ` }) export class ListComponent { @Input() items: Item[] = []; @Input() actions: Action[] = []; @Output() onActionEvent: EventEmitter<ActionEvent<Item>> = new EventEmitter<ActionEvent<Item>>(); doAction(name: string, payload: Item) { this.onActionEvent.emit({name, payload}) } }
It takes an
@Input
ofitems: Item[]
andactions: Actions[]
; the items to be displayed, and the supported actions of those items respectively.It also defines an
@Output
ofEventEmitter<ActionEvent<Item>>
to emit events for the items.The container component then, could be defined as such:
@Component({ selector: "container-component", template: ` <h1>Items</h1> <list-component [items]="this.items" [actions]="this.actions" (onActionEvent)="this.handleActionEvent($event)"> </list-component> ` }) export class ContainerComponent { items: Item[] = [ {name: "foo"}, {name: "bar"}, {name: "qux"}, ]; actions: Action[] = [ {name: "view"}, {name: "edit"}, ]; handleActionEvent(actionEvent: ActionEvent<Item>) { console.log(actionEvent); } }
This then resembles something such as:
Now, varying containers can define varying actions; some may support
view
andedit
, others may support different actions. I could easily add ashare
action (and the corresponding handler code, which could itself be wrapped up in theAction
type definition) and have something such as:Where I'm performing
console.log(actionEvent)
, the container's handler would be responsible for determining what meaningful behavior to perform onview
oredit
or whatever else.So, as stated at the top, am I painting myself into an undesirable corner with this approach? I'm trying to stay very DRY, but I feel like I'm straying away from KISS. Additionally, I'm as yet unaware of a built-in or more best-practices-conforming way to accomplish this.
-
How to get mouse event in terminal?
iam making terminal game, how to print mouse position in (windows) terminal window on mouse_button_1 click (no on the whole screen only in window)?
-
setState of multiple objects - React JS
I'm having problems when I want to update the state of an array and I am using the push() method to add the new values but apparently push does not update, so I have doubts if I can make a setState of multiple values.
Here's the code with the push() method:
buildDetailDB = () => { let {detail} = this.state; //console.log(detail) let dms=[]; detail.dms.map(fabric => { dms.push({ "line_id": fabric.line_id, "id": fabric.id, "dm": fabric.dm, "priceWhite": fabric.priceWhite, "priceMedium": fabric.priceMedium, "priceDark": fabric.priceDark, "priceSpecial": fabric.priceSpecial, "priceWhiteC": 0, "priceMediumC": 0, "priceDarkC": 0, "priceSpecialC": 0, "Blong": this.FixElementValue(fabric.Blong), "Bwidth": this.FixElementValue(fabric.Bwidth), "fabricType": fabric.fabricType, "weightBWashOriginal": this.FixElementValue(fabric.weightBWashOriginal), "weightBWashCalculated": this.FixElementValue(fabric.weightBWashCalculated), "dm_width": this.FixElementValue(fabric.dm_width), "markerWidth": this.FixElementValue(fabric.markerWidth), "dm_pt": fabric.dm_pt, "yieldydslbs": this.FixElementValue(fabric.yieldydslbs), "markerEfficiency": this.FixElementValue(fabric.markerEfficiency), "markerLong": this.FixElementValue(fabric.markerLong), "pieceByMarker": this.FixElementValue(fabric.pieceByMarker), "lbsunit": this.FixElementValue(fabric.lbsunit), "lbsunitwaste": this.FixElementValue(fabric.lbsunitwaste), "sqinchunit": this.FixElementValue(fabric.sqinchunit), "ydsunit": fabric.ydsunit, "bydspunit": this.FixElementValue(fabric.bydspunit), "blbspunit": this.FixElementValue(fabric.blbspunit), }) console.log(fabric) return fabric; });
-
Flutter : setState outside
I'm new to Flutter and I just want to understand something about stateful widget. Here's a simple code that works perfectly just by switching the text color from red to blue when clicking on a button :
import 'package:flutter/material.dart'; class MyWidget extends StatefulWidget { MyWidget({Key? key}) : super(key: key); @override State<MyWidget> createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { Color myColor = Colors.red; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("My app")), body: Column( children: [ Text( "Just a simple text", style: TextStyle(color: myColor), ), FloatingActionButton( onPressed: () { setState(() { myColor = (myColor == Colors.red) ? Colors.blue : Colors.red; }); print(myColor); }, child: Icon(Icons.home)), ], )); } }
My question is : if I get the column outside the stateful widget and call it as a component, how and where should I rewrite the setState function ? I begin with this code and I don't know how to continue :
import 'package:flutter/material.dart'; class MyWidget extends StatefulWidget { MyWidget({Key? key}) : super(key: key); @override State<MyWidget> createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { Color myColor = Colors.red; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("My app")), body: HomePage()); } } Column HomePage() { return Column( children: [ Text( "Just a simple text", style: TextStyle(color: myColor), // SHOULD I NOW INJECT myColor AS A PARAMETER OF HomePage ? ), FloatingActionButton( onPressed: () {print("WHERE TO PUT THE setState FUNCTION NOW ???")}, child: Icon(Icons.home)), ], ); }
-
setState not uodating on first call
// Get location manually and fetch weather data getSearchLocation = (value) => { const weatherApiLink = `https://api.openweathermap.org/data/2.5/weather?q=${value}&appid=${apiKeys.weatherKey}&units=metric`; this.setState({ weatherApiLink, value }) console.log(value) console.log(this.state.value) console.log(this.state.weatherApiLink) }
The getSearchLocation gets its value from other components using props and is run on the onClick function. when the above function is executed and we run the conslole.log(value) it returns the correct value but when we run console.log(this.state.value) it returns UNDEFINED on the first click, on the second click the state is updated