ReactJs Print value instantly - javascript

I am new to reactjs and trying to print update value of input field. What I firstly tried was this:
var App = React.createClass({
render() {
return <div>
<h1>Hello, {this.props.name}</h1>
<input type="text" onKeyUp={this.handleChange} />
<p>{this.handleChange}</p>
</div>;
},
handleChange: function(event) {
return event.target.value;
}
});
App = React.createFactory(App);
React.render(
<App name="World" />,
document.getElementById('mount-point'));
But I don't get it why it is not working. Than I tried this: CodePen maybe someone can help me with printing instantly the value of the input field in the <p> element

var App = React.createClass({
getInitialState: function() {
return {
text: "",
};
},
handleChange: function(event) {
this.setState({ text: event.target.value });
},
render() {
return <div>
<h1>Hello, {this.props.name}</h1>
<input type="text" onChange={this.handleChange} />
<p>{this.state.text}</p>
</div>;
},
});
You must store all state of the component in this.state. Use this.setState to update the state. When you update the state, the component is automatically rerendered with the new state.
The content of the paragraph is the current value of the state. onChange is commonly used instead of onKeyUp to handle changes of state in text inputs. handleChange will update the state when the text input changes.

Related

Cant get a text box state to refresh with user input, keeps going to default state despite using setState

I have a React file which displays a list of city data as a component. there is an input textbox above it which needs to accept user input. i am using state to display an initial string in the textbox, but i cannot get onChange to successfully use a function to setState. troubleshooting it with console.log i can see that when i attempt to change the state the function i am pointing to with onChange does work and changes one letter, but then the state snaps back to its default value. the problem seems to be with setState not saving the change and reverting back to the initial state after any changes are made. the text box content appears to not change at all, thought console.log shows a one letter change but then reverts back to the original state.
how do i update state? i want the user to be able to punch a number in and then compare it with the list.
import React, {Component} from 'react';
import Table from './Table';
import cities from './Cities';
class App extends Component {
state = {
userInput: "Your City Population"
}
popChanger = (event) => {
this.setState( {userInput: event.target.value} );
//console.log(event.target.value);
}
yourCity = (
<div>
<input
type='text'
onChange={this.popChanger}
value={this.state.userInput}
/>
</div>
)
render() {
return (
<div className = "App">
{this.yourCity}
<Table characterData = {cities} />
</div>
);
}
}
export default App;
setState() is saving your changes, just not in the right place,
popChanger() is an arrow function and updates the state of the App component,
yourCity has it's own this so it doesn't know about the App state.
you can either cahnge yourCity to an arrow function that returns the html you want like
class TodoApp extends React.Component {
state = {
a: ''
};
YourCity = () => (
<div>
<input type="text" onChange={this.handleChange} value={this.state.a} />
</div>
}
handleChange = e => this.setState({a : e.target.value})
render() {
return (
<div>
<this.YourCity />
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
Or, create yourCity component outside and pass the handleChange as a prop :
const YourCity = props => (
<div>
<input type="text" onChange={props.handleChange} value={props.value} />
</div>
)
class TodoApp extends React.Component {
state = {
a: ''
};
handleChange = e => this.setState({a : e.target.value})
render() {
return (
<div>
<YourCity handleChange={this.handleChange} value={this.state.a}/>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
The state is updating but you can't see that because this.yourCity doesn't re-render
popChanger = (event) => {
this.setState( {userInput: event.target.value} );
console.log(event.target.value);
}
yourCity(){
return <div>
<input
type='text'
onChange={this.popChanger}
value={this.state.userInput}
/>
</div>
}
render() {
return (
<div className = "App">
{this.yourCity()}
</div>
);
}
}

How to reset State in React so the view updates

I am trying to reset a input field on state update. So when my state updates through a function my view would change as well. Below is my code:
constructor(props){
super(props)
this.state = { song: '',
videos: '' }
this.handleSongInput = this.handleSongInput.bind(this)
}
in my render function I do something like this
render () {
return (
<div>
<TextField
floatingLabelText="Search Songs"
value={this.state.value}
onChange={this.handleSongInput}
/>
<br />
<RaisedButton label="Search" onClick={this.searchSong} />
</div>
)
}
The handle function for the Input field is below. It is simply setting the state.
handleSongInput = (e) => {
this.setState({ song: e.target.value})
}
Now on button click I have the following function which resets the initial
searchSong = () => {
...
this.setState({song:''})
}
Now if I do a console.log I can see that the state has changed. But in my view I can still see that the text field is populated with previous text.
How can I set the value of textfield with current state
I believe you have a variable name issue:
value={this.state.value}
should read:
value={this.state.song}

Accessing React component's props

Alright so I'm tinkering with ReactJS and working on simple examples, everything working great and I already feel it has improved my productivity. Now I am working on a simple React example that takes an app name and logs it to console when the Enter key press is detected. Everything working fine until I enter the app name in the input box and I press the Enter key, what I see then in the console log isn't the input value, but rather an "undefined" value. Here's the full JS Code:
"use strict";
var InputText = React.createClass({
render() {
return <div><p>Please input the app name you wish to access:</p></div>
}
});
var InputBox = React.createClass({
onKeyPress(e) {
if (e.key === 'Enter') {
console.log(this.props.value);
}
},
render() {
return <input type="text" onKeyPress={this.onKeyPress}></input>
}
});
var AppForm = React.createClass({
render() {
return <div class="appForm">
<InputText />
<InputBox />
</div>
}
});
var App = React.createClass({
render() {
return <AppForm />
}
});
ReactDOM.render(
<App />,
document.getElementById("container")
);
That's because you are not passing the value as a prop to your InputBox component.
You can get the value from the event
var InputBox = React.createClass({
onKeyPress(e) {
if (e.key === 'Enter') {
console.log('InputBox Value: ' + e.target.value);
}
},
render() {
return <input type="text" onKeyPress={this.onKeyPress}></input>
}
});
jsfiddle
Or store the value in the state and get it from there.
var InputBox = React.createClass({
onKeyPress(e) {
if (e.key === 'Enter') {
console.log('InputBox Value: ' + this.state.value);
}
},
render() {
return <input type="text" onKeyPress={this.onKeyPress} onChange={(e) => this.setState({value: e.target.value})}></input>
}
});
jsfiddle
you didnt pass any props into . You would pass props like this
there are no props passed anywhere in this app actually :)
But what you really want is the value from the input box. So in React you'd make a reference. As a quick and dirty example I have a global context object ctx={}
<input type="text" className="inputClass" style={inputStyles} ref={(c) => ctx._input = c} />
Now in my component I can refer to the value typed as
ctx._input.value
Console.log that and it should be all good.
Use ref to access the value of input box
"use strict";
var InputText = React.createClass({
render() {
return <div><p>Please input the app name you wish to access:</p></div>
}
});
var InputBox = React.createClass({
onKeyPress(e) {
if (e.key === 'Enter') {
console.log(this.refs.textbox.value);
}
},
render() {
return <input type="text" onKeyPress={this.onKeyPress} ref = 'textbox'></input>
}
});
var AppForm = React.createClass({
render() {
return <div class="appForm">
<InputText />
<InputBox />
</div>
}
});
var App = React.createClass({
render() {
return <AppForm />
}
});
ReactDOM.render(
<App />,
document.getElementById("container")
);
JSFIDDLE
Another way to obtain value will to use the event e as e.target.value. Props doesnt work because you are not actually passing props to the InputBox component.

When using onChange with React, spaces are not registered

I am trying to save a user's input by using the onChange method described here: https://facebook.github.io/react/docs/forms.html.
I have this line of code for my input:
<input type="text" onChange={this.changeTitle} ref="title" value={this.props.quiz ? this.getTitle() : ''}></input>
However, when I call this.refs.title.value after pressing the spacebar, the space is not registered. Is there anyway I can register this space?
Something as
var ChangeValue = React.createClass({
getInitialState() {
return { currentValue: '' };
},
onValueChange: function (evnt) {
this.setState({ currentValue: evnt.target.value });
},
render: function() {
return (
<div>
<input type="text" onChange={this.onValueChange} />
<p>
Current value is: <b>{this.state.currentValue}</b>
</p>
</div>
);
}
});
React.render(<ChangeValue />, document.body);
Just change onValueChange method to do what you need.
Live example: http://jsbin.com/xayowaloxa/edit?html,js,output

Get value from input and use on the button

I'am creating component with input element and button element.
I need to get the input value and use with button, for example. How can I do that?
Here's my code:
var InputSearch = React.createClass({
getInitialState: function() {
return {
value: 'pics'
}
},
handleChange: function() {
this.setState({
value: event.target.value
});
},
render: function() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange} />
)
}
});
var ButtonSearch = React.createClass({
handleClick: function(event) {
console.log(this.state.value); // here's go the input value
},
render: function() {
return (
<button onClick={this.handleClick}>GO! </button>
)
}
});
var Search = React.createClass({
render: function() {
return (
<div>
<InputSearch />
<ButtonSearch />
</div>
)
}
});
React.render(
<Search />,
document.getElementById('result')
);
One issue here is that you are breaking a good rule - separate smart and dumb components. https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
The way to do this is to have a parent component that holds all the state and functionality of the children and passes all of this down as props...
//Our smart parent
var SearchContainer = React.createClass({
getInitialState : function() {
return {
value : 'pics'
}
},
handleInput : function(event) {
this.setState({value: event.target.value});
},
render : function() {
return (
<div>
<InputSearch value={this.state.value} onChange={this.handleInput} />
<ButtonSearch value={this.state.value} />
</div>
)
}
});
//Our dumb children
var InputSearch = React.createClass({
propTypes : {
onChange : React.PropTypes.func.isRequired,
value : React.PropTypes.string
},
render : function() {
return (
<input type="text" value={this.props.value} onChange={this.props.onChange} />
)
}
});
var ButtonSearch = React.createClass({
propTypes : {
value : React.PropTypes.string
},
handleClick : function() {
console.log(this.props.value); //log value
},
render : function() {
return (
<button onClick={this.handleClick}>GO! </button>
)
}
});
React.render(<Search />, document.getElementById('result'));
Here we pass the handler function down from parent to child so the input doesn't care what happens to the event it fires on change, it just needs to know that it has a prop called onChange that's a function and it invokes that.
The parent (SearchContainer) handles all of that functionality and passes the changed state down to both the button and the input...
hope that helps
Dan
You left out the event in your handleChange.
handleChange: function(event) {
this.setState({
value: event.target.value
});
},
The main architecture of react is the Parent Child / Master Slave principle.
If you want to pass values between components you have to create relations between.
Like for example
You create your master Component with few default states.
var MyMasterComponent = React.createClass({
getInitialState: function(){
...
},
render: function(){
return(
<ChilComponent1 textiwanttopass={this.state.text} />
);
}
});
With that method you are calling the render of another component within a master component. That way you can pass values from states into another component.
In that case you can access the passed text with this.props.textiwanttopass

Categories