How can I use the value of state x in handleClick function to show an alert of input value in state x using Function component?
import React, { useState } from "react";
import "./App.css";
function About() {
const [state, setState] = useState({
x: "",
output: [],
});
//for onChange Event
const handleChnage = (e) => {
setState({ ...state, [state.x]: e.target.value });
console.log(e.target.value);
};
//for onClick Event
const handleClick = () => {
alert(state.x);
};
return (
<>
<h1>This is about about </h1>
<input
placeholder="Enter a number"
value={setState.x}
onChange={handleChnage}
/>
<button onClick={handleClick}>get Table</button>
</>
);
}
export default About;
It should be x instead of state.x
const handleChnage = (e) => {
setState({ ...state, x: e.target.value })
}
and the value should be state.x here instead of setState.x:
<input
placeholder="Enter a number"
value={state.x}
onChange={handleChnage}
/>
Remember on hooks, the first parameter is the value, the second parameter is the setter function.
Two issues should be fixed:
You do not need the computed value [state.x], it should be just x.
setState({ ...state, x: e.target.value });
The value for the input should be state.x not setState.x
<input
placeholder="Enter a number"
value={state.x}
onChange={handleChnage}
/>
function About() {
const [state, setState] = React.useState({
x: "",
output: []
});
//for onChange Event
const handleChnage = (e) => {
setState({ ...state, x: e.target.value });
console.log(e.target.value);
};
//for onClick Event
const handleClick = () => {
alert(state.x);
};
return (
<React.Fragment>
<h1>This is about about </h1>
<input
placeholder="Enter a number"
value={state.x}
onChange={handleChnage}
/>
<button onClick={handleClick}>get Table</button>
</React.Fragment>
);
}
ReactDOM.render(<About />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div class='react'></div>
Related
Having this code snippet:
const MyComponent = ({ e }) => {
const toggleButton = (e) => {
console.log('eee: ', e.target.value);
};
return (
<div>
<div>
<input className='input-search' type='text' placeholder='search' />
<Button onClick={(e) => toggleButton(e)}>reset</Button>
</div>
</div>
);
};
I was expecting to see in the log the value from input but it is undefined. Any thoughts?
e.target is the button which has no value attribute. You should be storing the input value in state with a onChange event. Make sure that the input's value attribute reflects the state, and use useEffect to log the changes to the console.
const {useState, useEffect} = React;
function Example() {
const [input, setInput] = useState('');
useEffect(() => {
console.log(`State: ${input}`);
}, [input])
function handleClick() {
setInput('');
}
function handleInput(e) {
const { target: { value } } = e;
setInput(value);
}
return (
<div>
<div>
<input onChange={handleInput} type="text" placeholder="search" value={input} />
<button onClick={handleClick}>reset</button>
</div>
</div>
);
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
i’m trying to sum two inputs and give a result with a button , i have defined the state hooks and they work but i don’t know how to pass the current state to a function and sum it.
Can you please help me?
i’m a beginner
here’s my code:
import React from 'react';
export default function Suma (){
//hook defined
const [input, setInput] = React.useState({
num1: "",
num2: "",
});
//handle input change
const handleInput = function(e){
setInput({
...input,
[e.target.name]: e.target.value
});
};
//suma function
const suma = function(){
}
return (
<div>
<input onChange={handleInput} name="num1" value={input.num1} type="text"></input>
<input onChange={handleInput} name="num2" value={input.num2} type="text"></input>
<button>+</button>
<span>resultado</span>
</div>
)
};
If you only want to show the result on click, I think this should be enough
export default function Suma (){
//hook defined
const [input, setInput] = React.useState({
num1: "",
num2: "",
});
const [result, setResult] = React.useState("")
//handle input change
const handleInput = function(e){
setInput({
...input,
[e.target.name]: e.target.value
});
};
//suma function
const suma = function(){
const { num1, num2 } = input;
setResult(Number(num1) + Number(num2));
}
return (
<div>
<input onChange={handleInput} name="num1" value={input.num1} type="number"></input>
<input onChange={handleInput} name="num2" value={input.num2} type="number"></input>
<button onclick={suma}>+</button>
<span>resultado: {result}</span>
</div>
)
};
import React from 'react';
export default function Suma (){
//hook defined
const [input, setInput] = React.useState({
num1: "",
num2: "",
});
const [sum, setSum] = React.useState(undefined)
useEffect(() => {
setSum(parseInt(input.num1) + parseInt(input.num2))
}, [input])
//handle input change
const handleInput = function(e){
setInput({
...input,
[e.target.name]: e.target.value
});
};
return (
<div>
<input onChange={handleInput} name="num1" value={input.num1} type="text"></input>
<input onChange={handleInput} name="num2" value={input.num2} type="text"></input>
<button>+</button>
{sum !== undefined && <span>{sum}</span>}
</div>
)
};
function AddForm() {
const [sum, setSum] = useState(0);
const [num, setNum] = useState(0);
function handleChange(e) {
setNum(e.target.value);
}
function handleSubmit(e) {
setSum(sum + Number(num));
e.preventDefault();
}
return <form onSubmit={handleSubmit}>
<input type="number" value={num} onChange={handleChange} />
<input type="submit" value="Add" />
<p> Sum is {sum} </p>
</form>;
}
Hello this is my first question here and I am just a beginner in Reactjs I need your explanation, please
the code is about Controlled Form wrote in-class component using "this.state".
I was trying time to turn it into a functional component using hooks with the same results
1- onSubmit render text on the screen
2- reset input into ""
the problem is no results going write and instead I got [object, Object] in the search
this is code
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
submit: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value
});
}
handleSubmit(event) {
event.preventDefault()
this.setState({
submit: this.state.input,
input:''
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type='text'
value={this.state.input}
onChange={this.handleChange}
/>
<button type='submit'>Submit!</button>
</form>
<h1>{this.state.submit}</h1>
</div>
);
}
}
The code at codesandbox for fast access
please can you tell me how to solve it?
thank you
Here is what you need https://codesandbox.io/s/new-leftpad-1n0yy, you can compare your current MyForm with Form to understand the difference, but I suggest to check documentation deeper
Here is the answer by Artem Matiushenko he added the second component using useState, useCallback
now we can compare the two types for controlled form
import React, { useCallback, useState } from "react";
import "./styles.css";
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
input: "",
submit: "",
};
}
handleChange = (event) => {
this.setState({
input: event.target.value,
});
};
handleSubmit = (event) => {
event.preventDefault();
this.setState({
submit: this.state.input,
input: "",
});
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.input}
onChange={this.handleChange}
/>
<button type="submit">Submit!</button>
</form>
<h1>{this.state.submit}</h1>
</div>
);
}
}
//using hooks------->
function Form() {
const [value, setValue] = useState("");
const [submitedValue, setSubmitedValue] = useState();
const handleOnChange = useCallback(({ target }) => {
setValue(target.value);
}, []);
const handleOnSubmit = useCallback(
(event) => {
event.preventDefault();
setSubmitedValue(value);
setValue("");
},
[value]
);
return (
<div>
<form onSubmit={handleOnSubmit}>
<input type="text" value={value} onChange={handleOnChange} />
<button type="submit">Submit!</button>
</form>
<h1>{submitedValue}</h1>
</div>
);
}
export default function App() {
return (
<div className="App">
<h1>Class Component Form</h1>
<h2>controlled form</h2>
<MyForm />
<Form />
</div>
);
}
here is mine after I understood how useSate works
const MyForm = () => {
const [input, setInput] = useState("");
const [submitText, setSubmitText] = useState("");
const handleChange = (event) => {setInput(event.target.value)};
const handleSubmit = (event) => {
event.preventDefault();
setSubmitText(input);
setInput("");
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" value={input} onChange={handleChange} />
<button type="submit">Submit!</button>
</form>
<h1>{submitText}</h1>
</div>
);
};
I have this react functional component where I have file input .
after I choose the file I assume the text in h1 tag should convert from
choose file to test but nothing happen
the handleChange function gets fired
the console.log print state.show : true
the INSIDE console.log() print state.show : true but does not show the string test
import React, { useState } from 'react';
export default ({ selectedFile }) => {
const [state, setState] = useState({});
const handleChange = e => {
console.log('in handleChange');
setState({ ...state, show: true });
};
console.log('My state: ', state);
return (
<div className='file-uploader'>
<input type='file' id='upload' hidden onChange={handleChange} />
<label htmlFor='upload'>
{state.show ? <h1> {console.log('INSIDE ', state)} test</h1> : <h1>choose file</h1>}
</label>
</div>
);
};
You need the following property {show: false} in your initial state.
import React, { useState } from 'react';
export default ({ selectedFile }) => {
const [state, setState] = useState({show: false});
const handleChange = e => {
console.log('in handleChange');
setState({ ...state, show: true });
};
console.log('My state: ', state);
return (
<div className='file-uploader'>
<input type='file' id='upload' hidden onChange={handleChange} />
<label htmlFor='upload'>
{state.show ? <h1>test</h1> : <h1>choose file</h1>}
</label>
</div>
);
};
Live Demo
I have a React Form app with name and description fields.
The form data is held in a local state object using Hooks:
const [data,setData] = useState({name: '', description: ''}).
The <Form /> element creates inputs and passes their value using <Field initialValue ={data.name} />
Within the <Field /> element, this initialValue is passed to the state, which controls the input value (updated onChange):
const [value,setValue] = useState(initialValue).
But if I reset the data object (see handleResetClick function), the inputs don't clear (even though the data object clears). What am I doing wrong? I thought that changing the data would cause a re-render and re-pass initialValue, resetting the input.
Codepen example here - when I type in the inputs, the data object updates, but when I click Clear, the inputs don't empty.
function Form() {
const [data, setData] = React.useState({name: '', description: ''});
React.useEffect(() => {
console.log(data);
},[data]);
const onSubmit = (e) => {
// not relevant to example
e.preventDefault();
return;
}
const handleResetClick = () => {
console.log('reset click');
setData({name: '', description: ''})
}
const onChange = (name, value) => {
const tmpData = data;
tmpData[name] = value;
setData({
...tmpData
});
}
return (
<form onSubmit={onSubmit}>
<Field onChange={onChange} initialValue={data.name} name="name" label="Name" />
<Field onChange={onChange} initialValue={data.description} name="description" label="Description" />
<button type="submit" className="button is-link">Submit</button>
<button onClick={handleResetClick} className="button is-link is-light">Clear</button>
</form>
)
}
function Field(props) {
const {name, label, initialValue, onChange} = props;
const [value, setValue] = React.useState(initialValue);
return (
<div>
<div className="field">
<label className="label">{label}</label>
<div className="control">
<input
name={name}
className="input"
type="text"
value={value}
onChange={e => {
setValue(e.target.value)
onChange(name, e.target.value)
}}
/>
</div>
</div>
</div>
)
}
class App extends React.Component {
render() {
return (
<div className="container">
<Form />
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
)
On handleResetClick you change the data state of Form, but it doesn't affect its children.
Try adding a listener for initialValue change with useEffect:
function Field(props) {
const { name, label, initialValue, onChange } = props;
const [value, setValue] = React.useState(initialValue);
useEffect(() => {
setValue(initialValue);
}, [initialValue]);
return ...
}
You may be better off having Field as a controlled component (ie it's state is managed by the parent component rather than maintaining its own state). In this example I've swapped in value instead of initialValue and simply passed that down as props to the field. onChange then calls the parent method and updates the state there (which is automatically passed back down to the field when it renders):
const { useState, useEffect } = React;
function Form() {
const [data, setData] = React.useState({
name: '',
description: ''
});
useEffect(() => {
console.log(data);
}, [data]);
const onSubmit = (e) => {
e.preventDefault();
return;
}
const handleResetClick = () => {
setData({name: '', description: ''})
}
const onChange = (e) => {
const { target: { name, value } } = e;
setData(data => ({ ...data, [name]: value }));
}
return (
<form onSubmit={onSubmit}>
<Field onChange={onChange} value={data.name} name="name" label="Name" />
<Field onChange={onChange} value={data.description} name="description" label="Description" />
<button type="submit" className="button is-link">Submit</button>
<button onClick={handleResetClick} className="button is-link is-light">Clear</button>
</form>
)
}
function Field(props) {
const {name, label, value, onChange} = props;
return (
<div>
<div className="field">
<label className="label">{label}</label>
<div className="control">
<input
name={name}
className="input"
type="text"
value={value}
onChange={onChange}
/>
</div>
</div>
</div>
)
}
function App() {
return (
<div className="container">
<Form />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>