input form sending blank value in reactjs - javascript

i am trying to console.log the input value using react. below is the code i have written
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component{
constructor() {
super();
this.processHand = this.processHand.bind(this);
}
processHand(e){
e.preventDefault();
const handMoneyReceived = this.handMoney.value;
console.log(handMoneyReceived);
}
render(){
return(
<div>
<form onSubmit = {this.processHand}>
<input type="text"/>
<input type="submit" ref= {ref => this.handMoney = ref}/>
</form>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
the console.log(handMoneyReceived) is logging out blank value instead of value entered on the form.

Because you used ref on wrong field, use it with text field, try this:
<input type="text" ref= {ref => this.handMoney = ref}/>
Check the working fiddle: https://jsfiddle.net/mayankshukla5031/k1efLh8e/

Related

Quick way to reference an element in a React component?

I have a component that has an input field and button. I want to add an onclick handler on the button that uses the value of the input. I can do this with querySelector, or getElementbyId or having a parent form element, or changing the input to a component. But what I want to know is if there's a direct and easy way just to refence the element.
import React from "react";
export default class UserInput extends React.Component{
constructor(props){
super(props);
this.doStuff = this.doStuff.bind(this);
}
doStuff(){
const inputValue = document.getElementById('new-task').value // I want to replace this
// do stuff
}
render(){
return(
<div id="user-input">
<input type="text" id="new-task"></input>
<button type="button" onClick={this.doStuff}>Do Stuff!</button>
</div>
)
}
}
I think you can do it this way. Just give it a try.
import React from "react";
export default class UserInput extends React.Component{
constructor(props){
super(props);
this.textInput = React.createRef();
this.doStuff = this.doStuff.bind(this);
}
doStuff(){
const inputValue = this.textInput
}
render(){
return(
<div id="user-input">
<input type="text" id="new-task" ref={this.textInput}></input>
<button type="button" onClick={this.doStuff}>Do Stuff!</button>
</div>
)
}
}

How to update react component state from one component to another, and call any functions from any component

I am very new to react, when I put everything in one place, it works fine. But when I split it into components, everything went wrong.
I have two files App.js and Activity1.js
Activity1.js contains an input with an event handler attached to it. This input is simply wrapped inside a div.
The input was initially in App.js but I extracted it to Activity.js.
The input has a sibling, a div where I echo whatever the user types in the input, by updating the props state. How can I update the state. Your time and interest is appreciated.
Here's my code:
App.js
import './App.css';
import React from 'react';
import Activity1 from './f/Activity1';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {value:15};
}
checkInput = e => {
this.setState({value: e.target.value});
}
render(){
return (
<div className="p-2">
<div>
<Activity1 />
</div>
</div>
)
}
}
export default App;
Here's Activity1.js
import React from "react";
class Activity1 extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<div>
<div>Enter Number</div>
<input className="form-control" onChange={this.checkInput} />
<div className="p-2 mt-3">{this.state.value}</div>
</div>
)
}
}
export default Activity1;
Hope this solves the problem.
app.js
...
<Activity1 checkInput = {this.checkInput} inputValue = {this.state.value}/>
...
Activity1.js
...
render() {
const {checkInput, inputValue} = this.props;
...
<input className = "form-control" onChange = {checkInput} />
<div className = "p-2 mt-3"> {inputValue} </div>
You can pass a function as a prop to the other component.
<div>
<Activity1 checkInput={this.checkInput} inputValue = {this.state.value}/>
</div>
In your Activity1 component,
const {checkInput, inputValue} = this.props;
onChangeEventHandler= () => {
checkInput();
}
and
<input className = "form-control" onChange = ={this.onChangeEventHandler} />
<div className = "p-2 mt-3"> {this.inputValue} </div>
https://dev.to/vadims4/passing-down-functions-in-react-4618
You can use a Callback function
<Activity checkInput = {this.checkInput} inputValue = {this.checkInput.bind(this)}/>

Live updates between React components based on state

My (simplified) goal:
Show a form input's text content beside the form itself and update the reflected text as the input text changes. The form lives within a React component, and the displayed text lives inside another one.
I can use the component state to control the input's text and change the state based on onChange form event. But how can I also change the state of the displayed text so that I get the live updates I'm looking for?
Input and output components have the same parent component.
Here's my input component:
import React, { useState } from "react";
function InputBoxTest() {
const [inText, setInText] = useState("");
const handleChange = event => {
setInText(event.target.value);
// My instinct is to setOutText here, but I can't...
};
return (
<textarea className="form-control" id="comment" onChange={handleChange}>
{inText}
</textarea>
);
}
export default InputBoxTest;
My output component:
import React, { useState } from "react";
function OutputBoxTest() {
const [outText, setOutText] = useState("");
return <p>{outText}</p>;
}
export default OutputBoxTest;
And my parent component:
import React from "react";
import InputBoxTest from "./InputBoxTest";
import OutputBoxTest from "./OutputBoxTest";
function Test1(props) {
return (
<>
<div className="row">
<div className="container-fluid col-sm-7">
<InputBoxTest />
</div>
<div className="col-sm-5">
<OutputBoxTest />
</div>
</div>
</>
);
}
export default Test1;
You could move the State Hook from InputBoxText into the ParentComponent Test1
InputBoxText is then used for displaying and updating the state
OutputBoxText is used for displaying only
import React from "react";
import InputBoxTest from "./InputBoxTest";
import OutputBoxTest from "./OutputBoxTest";
function Test1(props) {
const [inText, setInText] = useState("");
const handleChange = event => {
setInText(event.target.value);
};
return (
<>
<div className="row">
<div className="container-fluid col-sm-7">
<InputBoxTest text={inText} handleChange={handleChange} />
</div>
<div className="col-sm-5">
<OutputBoxTest text={inText}/>
</div>
</div>
</>
);
}
export default Test1;
function InputBoxTest(props) {
return (
<textarea className="form-control" id="comment" onChange={props.handleChange}>
{props.text}
</textarea>
);
}
export default InputBoxTest;
function OutputBoxTest(props) {
return <p>{props.text}</p>;
}
export default OutputBoxTest;
If you need to share some state between 2 components, you need to move that state in their (at least first) parent. You can read more about it here.
Basically what this means is that your Test1 component should be holder of your textarea value.
Please see this example based on your code.

ReactJS and autofocus

I have a react-bootstrap modal with an <input>. I want to set the autofocus attribute on the <input>
The following works fine, but shows a warning in the console
<input type="text" autofocus='true' />
Warning: Invalid DOM property `autofocus`. Did you mean `autoFocus`?
The following options do not work, in the sense that they do not focus the input when opening the modal:
<input type="text" autoFocus='true' />
<input type="text" autoFocus={true} />
<input type="text" autoFocus />
What is the recommended way of setting autofocus. Or how should I mute the warnings for the example that works well?
Note: This is react 16.8.6
If you're using React Hooks, add useCallback() to your component and add a ref={callback} to the form control:
import React, { useCallback } from 'react'
function InputComponent() {
const autoFocus = useCallback(el => el ? el.focus() : null, [])
return <input type="text" ref={autoFocus} />
}
export default InputComponent
You can replace the <input> with a React Bootstrap FormControl too.
Refs is what you want,
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount(){
this.myRef.current.focus();
}
<input type="text" ref={this.myRef} />
If you are using react hooks, you could write your own simple auto focus hook:
import { useEffect, useState } from "react";
export const useAutoFocus = (inputId: string) => {
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if(!initialized) {
document.getElementById("email").focus();
setInitialized(true);
}
});
};
and the simply use e.g.
useAutoFocus("email")
in your form.

How to get label values dynamically and adding the numbers together from different input with reactjs

Created a Div and inside it I have label element and input element, I want to get different label values in each div. How to re-use my div component
instead of coding the same code again.
I have tried to search in Stackoverflow plus googles, Haven't received a better answer.
Here I have created div element with just label and input element and then I have rendured this component in App.js file:
How can I reuse the same code/component to create 2 more div and having different labels values in it? Ho can I add numbers together from different input ( which I am getting from different components input)
Appreciate all your help!
import React, { Component } from 'react';
import './calculator.css';
class Boxes extends Component {
state = {
inputOne: '',
inputtwo: '',
inputthree: ''
}
getInputValue = (e) => {
const value = e.target.value;
console.log('value: ', value);
this.setState({
inputOne: Number(e.target.value)
});
}
render() {
const { value } = this.props // destructuring
const {inputOne, inputtwo, inputthree } = this.state
return (
<div className="boxes">
<label className="boxeslevel" htmlFor="text">
{value}
</label>
<input
name="text"
type="text"
onChange={this.getInputValue}
/>
</div>
);
}
}
export default Boxes;
import React, { Component } from 'react';
import './App.css';
import Boxes from './components/calculator';
class App extends Component {
render(){
return (
<div className="wrapper">
<Boxes value= {"Value 1:"} onChange={this.props.onChange}/>
<Boxes value= {"Value 2:"} onChange={this.props.onChange}/>
<Boxes value= {"Value 3:"} onChange={this.props.onChange}/>
<ShowResult />
</div>
);
}
}
export default App;
You should pass a prop to your componente to be reuse. As you notice you are using local component state in your component, like const {value} = this.state try the same approach but with props like const {value} = this.props and then passing that prop in the component usage like
<Boxes value={“label 1”}/>
<Boxes value={“label 2”}/>
That would work. Hope it help you
Remember you can use as many props you need and access them as the same way mention above
You can do something like this:
class Boxes extends Component {
render() {
const { value } = this.props // value coming from props
return (
<div className="wrapper">
<div className="firstBox">
<label htmlFor="text">
{value}
</label>
<input name="text" type="text" />
</div>
</div >
);
}
}
export default Boxes;
and in your app component something like this:
import React, { Component } from 'react';
import './App.css';
import Boxes from './components/calculator';
class App extends Component {
render(){
return (
<div className="App">
<Boxes value={1}/>
<Boxes value={2}/>
<Boxes value={3}/>
</div>
);
}
}
export default App;
Here is live demo link
You have to use props instead of state in your Boxes component. Then you can pass the required props from the App component.
App.js
import React, { Component } from 'react';
import './App.css';
import Boxes from './components/calculator';
class App extends Component {
render(){
return (
<div className="App">
<Boxes value={"Value 1"}/>
<Boxes value={"Value 2"}/>
<Boxes value={"Value 3"}/>
</div>
);
}
}
export default App;
Boxes.js
import React, { Component } from 'react';
import './calculator.css';
class Boxes extends Component {
render() {
const { value } = this.props // destructuring
return (
<div className="wrapper">
<div className="firstBox">
<label htmlFor="text">
{value}
</label>
<input name="text" type="text" />
</div>
</div >
);
}
}
export default Boxes;

Categories

Resources