How can I use "Enter" button to setState to my component - javascript

I'm a real beginner with ReactJs Es6, I'm trying to setState to my component when I hit the "Enter" Button, I have tried some of the answers here, like this one, https://stackoverflow.com/a/34634290/8301413, but it hasn't worked the way I want to.
What I have so far is when I enter a text on my input box, the <h1> changes it's state and displays the state with every character input. What I want to happen is, I input my text first, then when I hit enter, that's the only time the state updates and displays the text from the input box.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export class App extends Component {
constructor(props) {
super(props);
this.state = { userInput: '' };
this.handleUserInput = this.handleUserInput.bind(this);
}
handleUserInput(e) {
this.setState({userInput: e.target.value});
}
render() {
return (
<div>
<input
type="text"
value={this.state.userInput}
onChange={this.handleUserInput}
/>
<h1>{this.state.userInput}</h1>
</div>
);
}
}
export default App;

To achieve that behaviour use uncontrolled component, means don't use the value property of input element. Instead of using onChange event use onKeyDown and check the keyCode, update the state only when user press the enter key.
Check this working snippet:
class App extends React.Component {
constructor(props) {
super(props);
this.state = { userInput: '' };
this.handleUserInput = this.handleUserInput.bind(this);
}
handleUserInput(e) {
if(e.keyCode == 13)
this.setState({userInput: e.target.value});
}
render() {
return (
<div>
<input
type="text"
onKeyDown={this.handleUserInput}
/>
<h1>{this.state.userInput}</h1>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<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='app'//>

#Mayank Shukla answer may be right, however it changes it to uncontrolled component.
Demo
You just need to add on more event onKeyPress which waits for "Enter" key.
class App extends React.Component {
constructor(props) {
super(props);
this.state = { userInput: '', output: '' };
this.handleUserInput = this.handleUserInput.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleUserInput(e) {
if (e.key === 'Enter') {
this.setState({output: e.target.value});
}
}
handleChange(e) {
this.setState({userInput: e.target.value});
}
render() {
return (
<div>
<input
type="text"
value={this.state.userInput}
onKeyPress={this.handleUserInput} // Only for "Enter" purpose
onChange={this.handleChange}
/>
<h1>{this.state.output}</h1>
</div>
);
}
}
This way you still keep the component controlled.
Example of Controlled Component objective

Related

How to pass a value from a function to a class in React?

Goal
I am aiming to get the transcript value, from the function Dictaphone and pass it into to the SearchBar class, and finally set the state term to transcript.
Current code
import React from 'react';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
const Dictaphone = () => {
const { transcript } = useSpeechRecognition()
if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
return null
}
return (
<div>
<button onClick={SpeechRecognition.startListening}>Start</button>
<p>{transcript}</p>
</div>
)
}
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
term: ''
}
this.handleTermChange = this.handleTermChange.bind(this);
}
handleTermChange(event) {
this.setState({ term: event.target.value });
}
render() {
return (
<div className="SearchBar">
<input onChange={this.handleTermChange} placeholder="Enter some text..." />
<Dictaphone />
</div>
)
}
}
export { SearchBar };
Problem
I can render the component <Dictaphone /> within my SearchBar. The only use of that is it renders a button and the transcript. But that's not use for me.
What I need to do is, get the Transcript value and set it to this.state.term so my input field within my SearchBar changes.
What I have tried
I tried creating an object within my SearchBar component and called it handleSpeech..
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
term: ''
}
this.handleTermChange = this.handleTermChange.bind(this);
}
handleTermChange(event) {
this.setState({ term: event.target.value });
}
handleSpeech() {
const { transcript } = useSpeechRecognition()
if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
return null
}
SpeechRecognition.startListening();
this.setState({ term: transcript});
}
render() {
return (
<div className="SearchBar">
<input onChange={this.handleTermChange} placeholder="Enter some text..." />
<button onClick={this.handleSpeech}>Start</button>
</div>
)
}
}
Error
But I get this error:
React Hook "useSpeechRecognition" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
React Hooks must be called in a React function component or a custom React Hook function
Well, the error is pretty clear. You're trying to use a hook in a class component, and you can't do that.
Option 1 - Change SearchBar to a Function Component
If this is feasible, it would be my suggested solution as the library you're using appears to be built with that in mind.
Option 2
Communicate between Class Component <=> Function Component.
I'm basing this off your "current code".
import React, { useEffect } from 'react';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
const Dictaphone = ({ onTranscriptChange }) => {
const { transcript } = useSpeechRecognition();
// When `transcript` changes, invoke a function that will act as a callback to the parent (SearchBar)
// Note of caution: this code may not work perfectly as-is. Invoking `onTranscriptChange` would cause the parent's state to change and therefore Dictaphone would re-render, potentially causing infinite re-renders. You'll need to understand the hook's behavior to mitigate appropriately.
useEffect(() => {
onTranscriptChange(transcript);
}, [transcript]);
if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
return null
}
return (
<div>
<button onClick={SpeechRecognition.startListening}>Start</button>
<p>{transcript}</p>
</div>
)
}
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
transcript: ''
}
this.onTranscriptChange = this.onTranscriptChange.bind(this);
}
onTranscriptChange(transcript){
this.setState({ transcript });
}
render() {
return (
<div className="SearchBar">
<input onChange={this.handleTermChange} placeholder="Enter some text..." />
<Dictaphone onTranscriptChange={onTranscriptChange} />
</div>
)
}
}
useSpeechRecognition is a React hook, which is a special type of function that only works in specific situations. You can't use hooks inside a class-based component; they only work in function-based components, or in custom hooks. See the rules of hooks for all the limitations.
Since this hook is provided by a 3rd party library, you have a couple of options. One is to rewrite your search bar component to be a function. This may take some time if you're unfamiliar with hooks.
You can also see if the react-speech-recognition library provides any utilities that are intended to work with class-based components.

Parent state undefined in componentDidMount event of the child component

I'm setting the state of my parent component in componentDidMount and passing its value to a child component via props, but even though the input is filled, when I run console.log(this.props.value) in the componentDidMount event of the child component, it is undefined. I need this value updated in this event.
How to get the correct prop value in this scenario?
Example code:
class Text extends React.Component {
componentDidMount(){
console.log(this.props.value);
}
render() {
return (
<div>
<input type="text" value={this.props.value} />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount(){
let data = {
RequestId: "0000-000"
}
this.setState({ data });
}
render() {
return (
<Text value={this.state.data["RequestId"]} />
);
}
}
// Render it
ReactDOM.render(
<Form />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
What happen in your case is the child component mount before the logic change from the parent. Here a way to make it work. Also what you can do it's use the componentDidUpdate lifecycle method to trigger the change.
Remember componentDidMount get call only ONE time. So at the moment the parent get it the child is already mount. But as you can see the value of the input is filled that's because react component rerender on props change. BUT not REMOUNT.
With the if part here, the component render only when data RequestId is filled, so we can then trigger the componentDidMount with the value you want.
class Text extends React.Component {
componentDidMount(){
console.log(this.props.value);
}
render() {
return (
<div>
<input type="text" value={this.props.value} />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount(){
let data = {
RequestId: "0000-000"
}
this.setState({ data });
}
render() {
if (!this.state.data["RequestId"]) { return null }
return (
<Text value={this.state.data["RequestId"]} />
);
}
}
// Render it
ReactDOM.render(
<Form />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

React todo list displays todo onChange, not onSubmit

I'm a bit new to React, and with all new programming endeavors I am building a todo app. Everything seems to be working correctly except for one issue: When I enter a todo into the input field and click "submit", the todo is pushed into my array, however it doesn't immediately display. It is only when I change the text inside the input that the todo is displayed. I'm guessing this has something to do with the rendering happening on the handleChange function and not the handleSubmit function. Any help would be greatly appreciated.
Here is my AddTodo component
import React, { Component } from 'react';
import App from "./App"
import List from "./List"
class AddTodo extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
array: []
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
var array = this.state.array
array.push(this.state.value);
console.log(array)
}
render() {
return (
<div>
<form>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input onClick={this.handleSubmit} type="submit" value="Submit" />
</form>
<List array={this.state.array}/>
</div>
);
}
}
And my List component
import React, { Component } from 'react';
class List extends Component{
render(){
return(
<div>
{
this.props.array.map(function(item, index){
return <li key={index}>{item}</li>
})
}
</div>
)
}
}
export default List;
By default, invoking setState() calls the render() function.
More info here: ReactJS - Does render get called any time "setState" is called?
React renders an individual component whenever its props or state change. In order to make a change in the state, with a class component it's mandatory to use the this.setState() method, which among other things makes sure to call the render() when it's necessary.
Your handleSubmit() method is changing the array directly, which is forbidden (it's only allowed in the constructor in order to set the initial state)
If you use setState() it should work.

How to make/access state using props in react?

I made an app with multiple components and want their state to be accessed using parent/main app, I'm not sure how to get it. what i'm trying to do is when i change state in main "App" the component state should change. One of the component is 'checkbox' and now i want to access its state using parent app, I made multiple attempts but not getting it done. my code goes like this..
This is Main 'App' code:
import React, { Component } from 'react';
import Checkbox from './checkbox';
import Radio from './Radio';
import ToggleSwitch from './ToggleSwitch';
import PrimaryButton from './PrimaryButton';
class App extends Component {
onClick(isClicked){
isChecked:true
};
render() {
return (
<div id="form">
<Checkbox
onClick={this.onClick}
/>
<RadioButton
onClick={this.onClick}
/>
</div>
);
}
}
export default App;
The component i want to access goes like this:
import React, { Component } from 'react';
class Checkbox extends Component {
constructor(props){
super(props);
this.state={
isChecked:true
};
};
onCheck(){
this.setState({
isChecked: !this.state.isChecked
});
this.props.isClicked()
};
render() {
return (
<div>
<div
className={this.state.isChecked ? 'checked': 'unchecked'}
onClick={this.onCheck.bind(this)}
>
</div>
</div>
);
}
}
export default Checkbox;
You forgot to bind the onClick event in the app component, try this it will work :
class App extends Component {
onClick(isClicked){
console.log('isClicked', isClicked);
};
render() {
return (
<div id="form">
<Checkbox onClick={this.onClick.bind(this)}/>
</div>
);
}
}
If you already have onClick handler for the Checkbox I don't see why you couldn't just move the state up to the App component and just pass down a callback from there to the Checkbox that will update the parent state. That seems like a more React way to do it, to me.
class App extends Component {
constructor(props){
super(props);
this.state={
isChecked:true
}
}
onClick = (isClicked) => {
this.setState({isChecked: !this.state.isChecked})
}
render() {
return (
<div id="form">
<Checkbox
onClick={this.onClick}
ischecked={this.state.isChecked}
/>
</div>
);
}
}
Component
class Checkbox extends Component {
onCheck(){
this.props.onClick()
}
render() {
return (
<div>
<div
className={this.props.isChecked ? 'checked': 'unchecked'}
onClick={this.onCheck.bind(this)}
>
</div>
</div>
)
}
}

Is there a React lifecycle method to do something only when component receive props the first time?

I'm new to React so thank you for your patience in advance. Also using Redux.
I have a list of content pulled from the API, I display the text and a hidden text box and on a state change associated that alternates the visibility of the two. Essentially user can click on the text and edit the text, achieved by inverting the boolean and swapping the display. They can then save it and PUT to server etc.
Since my list length varies, I must initialize a number of state.isVisible[n]. equivalent to the number of content being displayed each time. This number must be counted, after the props come in. I am using Redux so the content is retrieved, stored, then given to props. It's done as the following:
constructor(props){
super(props);
this.state = {
isVisibleObj: {}
}
}
componentWillReceiveProps(){
const { isVisibleObj } = this.state
// set visibility of text box
let obj = {}
Object.keys(this.props.questions).forEach(key => obj[key] = false)
this.setState({isVisibleObj: obj})
}
My initial implementation was that in componentWillReceiveProps I do all the setState() to initialize the isVisible properties to a boolean.
The challenge I am having with this implementation is that, if a user open up multiple items for edit, and if she saves one of them, the PUT request on success would send back the edited content, now updating the store and props. This will trigger componentWillReceiveProps and reset all the visibilities, effectively closing all the other edits that are open.
Any suggestion on how to proceed?
I think you should make two components
List (NamesList.react)
import React, {PropTypes} from 'react';
import NameForm from './NameForm.react';
import Faker from 'Faker'
export default class NamesList extends React.Component {
constructor(){
super();
this.addItem = this.addItem.bind(this);
}
addItem(){
var randomName = Faker.name.findName();
this.props.addName(randomName);
}
render() {
let forms = this.props.names.map((name,i) => {
return <NameForm updateName={this.props.updateName} index={i} key={i} name={name} />
});
return (<div>
<div>{forms}</div>
<button onClick={this.addItem}>Add</button>
</div>);
}
}
NamesList.propTypes = {
names: PropTypes.arrayOf(PropTypes.string).isRequired
};
Form (NameForm.react)
import React, {PropTypes} from 'react';
export default class NameForm extends React.Component {
constructor(props) {
super(props);
this.updateName = this.updateName.bind(this);
this.state = {
showTextBox:false
}
}
updateName(){
this.setState({showTextBox:false});
this.props.updateName(this.props.index,this.refs.name.value);
}
render() {
if(this.state.showTextBox){
return (<div>
<input ref="name" defaultValue={this.props.name} />
<button onClick={this.updateName}>Save</button>
</div>);
}
return (<div onClick={() => {this.setState({showTextBox: !this.state.showTextBox})}}>
{this.props.name}
</div>);
}
}
NameForm.propTypes = {
name:PropTypes.string.isRequired
};
Invoke (App.js)
import React, { Component } from 'react';
import NamesList from './NamesList.react';
class App extends Component {
constructor(){
super();
this.addName = this.addName.bind(this);
this.updateName = this.updateName.bind(this);
this.state = {
names:['Praveen','Vartika']
}
}
addName(name){
let names = this.state.names.concat(name);
this.setState({
names: names
});
}
updateName(index,newName){
let names = this.state.names.map((name,i) => {
if(i==index){
return newName
}
return name;
});
this.setState({names:names});
}
render() {
return (
<NamesList names={this.state.names} updateName={this.updateName} addName={this.addName} />
);
}
}
export default App;
Now if your store changes after user saves something. React wont re-render Child component that didn't change

Categories

Resources