React updateState function - javascript

I have simple update data function which currently not working:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState() {
this.setState({data: 'Data updated...'})
}
render() {
return (
<div>
<button onClick = {this.updateState}>CLICK</button>
<h4>{this.data}</h4>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
Below I have link to jsbin:
http://jsbin.com/vidumiroki/edit?html,js,output

You missed state in you return render function
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState() {
this.setState({data: 'Data updated...'})
}
render() {
return (
<div>
<button onClick = {this.updateState}>CLICK</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'));

Related

Cannot send event handler to child element through props

I'm trying to send a form-submission handler to a child element through props. Everything renders, but when I click the submit button, I get no alert (see alert('Hi') in the handleSubmit function), and I also don't see the elements of SearchResults change. Instead, the whole page reloads and I'm back in the initial state. What is wrong?
Searcher.js:
class Searcher extends React.Component {
constructor(props) {
super(props);
this.state = {
results: [
{name:'1', key:0},
{name:'2', key:1}
]
};
}
handleSubmit = (event) => {
alert('Hi');
this.setState({
results: [
{name: 'hi', key: 0},
{name: 'again', key: 1}
]
})
event.preventDefault();
}
render() {
return (
<div>
<SearchForm/>
<SearchResults results={this.state.results} handleSubmit={this.handleSubmit}/>
</div>
)
}
}
export default Searcher;
SearchForm.js:
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) { this.setState({value: event.target.value}); }
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
);
}
}
export default SearchForm;
SearchResults.js:
class SearchResults extends React.Component {
render() {
return (
this.props.results.map((result) => (<div key={result.key}>{result.name}</div>))
)
}
}
export default SearchResults;
Passing handeSubmit as props in <SearchForm /> in Searcher.js
render() {
return (
<div>
<SearchForm handleSubmit={this.handleSubmit}/> // Pass Handle Submit
<SearchResults results={this.state.results} /> // I don't see handleSubmit being used in SearchResults
</div>
)
}
Try passing handleSubmit to SearchForm or its value will be undefined
class Searcher extends React.Component {
...
handleSubmit = (event) => {
alert('Hi');
...
}
render() {
return <SearchForm handleSubmit={this.handleSubmit}/>
}
}
export default Searcher;

What is the difference between this.state.function and this.function in ReactJS

I am learning the concept of States in React. I am trying to understand the difference between using this.handleChange, and this.state.handleChange.
I would be grateful if someone could explain to me, the exact difference between the two, and why would this.state.handleChange not work?
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
inputValue: event.target.value
});
}
render() {
return (
<div>
< GetInput input={this.state.inputValue} handleChange={this.handleChange} />
{ /* this.handleChanges, and this.state.handleChanges */ }
< RenderInput input={this.state.inputValue} />
</div>
);
}
};
class GetInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Get Input:</h3>
<input
value={this.props.input}
onChange={this.props.handleChange}/>
</div>
);
}
};
class RenderInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Input Render:</h3>
<p>{this.props.input}</p>
</div>
);
}
};
You can technically call this.state.handleChange so long as you add handleChange in your state.
But it doesn't really make sense since you don't want React to keep a track of it, and it will probably not change (unless you are doing some clever tricks).
constructor(props) {
super(props);
this.state = {
handleChange: e => {
e.preventDefault();
console.log("this.state.handleChange");
}
};
}
One would normally declare a member function in a class.
handleChange = e => {
e.preventDefault();
console.log("this.handleChange");
};
Here is the full working code
(working demo available on CodeSandBox).
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
handleChange: e => {
e.preventDefault();
console.log("this.state.handleChange");
}
};
}
handleChange = e => {
e.preventDefault();
console.log("this.handleChange");
};
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={this.handleChange}>this.handleChange</button>
<button onClick={this.state.handleChange}>
this.state.handleChange
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
When you say this.state.something this means something is in the state field of the class. When you say this.someFunction this means something is in the class itself. this here is pointing out our class.
class App extends React.Component {
state = {
something: "Something",
}
someFunction = () => console.log(this.state.something);
render() {
return (
<div>
<button onClick={this.someFunction}>Click</button>
</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"></div>
So, you can't use this.state.handleChange since there is no handleChange in the state. It is a function belongs to the class. This is why we use this.handleChange.
you can store a function in state
constructor(super){
super(props)
this.state = {
generateANumber: () => this.setState({ number: Math.floor(Math.random() * 100) }),
number: 0
}
}
then if you want to call it in your render method
render() {
return <p> {this.state.number} <button onClick={() => this.state.generateANumber()} Press Me To Generate A New Number </button> </p>
}
This is the concept of storing a function in state. This.function just means the function belongs to that class so you can use it using the this keyword.

ERROR: this.props.addNew is not a function

So I'm new to react and Ive been playing around with it for the past few weeks. I keep on getting this "ERROR: this.props.addNew is not a function" error about the addNew function within the addTheFriend function and I dont know why? Everything seems to correct to me. Can anybody help me? Thank you in advance.
import React, { Component } from 'react';
import { render } from 'react-dom';
export default class HelloUser extends React.Component {
constructor(props) {
super(props);
this.state = { name: "TT", friendsCount: 0 , friends: ["SS", "JJ", "Ww"] };
this.addFriends=this.addFriends.bind(this);
this.componentWillMount=this.componentWillMount.bind(this);
}
addFriends(friend) {
this.setState({
friends: this.state.friends.concat([friend]),
friendsCount: this.state.friendsCount + 1
});
}
componentWillMount() {
this.setState({
friendsCount: this.state.friends.length
});
}
render() {
return (
<div>
Villain: {this.state.name}, No of friends: {this.state.friendsCount}<br />
<AddingTheFriend addNew={this.addFriends} />
<ListFriends enemies={this.state.friends} />
</div>
);
}
};
export default class ListFriends extends React.Component {
render() {
var allFriends = this.props.enemies.map(function (friend) {
return <li>{friend}</li>;
});
return (
<div>
Her evil friends:
<ul>{allFriends}</ul>
</div>
);
}
};
export default class AddingTheFriend extends React.Component {
constructor(props) {
super(props);
this.state= {newFriend: ''};
this.updateNewFriend = this.updateNewFriend.bind(this);
this.addTheFriend = this.addTheFriend.bind(this);
}
updateNewFriend(change) {
this.setState({
newFriend: change.target.value
});
}
addTheFriend() {
this.props.addNew(this.state.newFriend);
this.setState({
newFriend: ''
})
}
render() {
return (
<div>
<input type="text" value={this.state.newFriend} onChange={this.updateNewFriend} />
<button type="button" onClick={this.addTheFriend}>Add Friend</button>
</div>
)
}
};
render(<HelloUser />, document.getElementById('root'));

Update the state of the grandparent component

I'd like to update a state value of the grandparent component:
class GrandChild extends React.Component {
changeNumber() {
// this.setState(prevState => ({
// number: prevState.number + 1 // Add 1
// }));
// I want to set the state of the App Component instead of the GrandChild component
}
render() {
return(
<div>
<h1>The number is {this.props.number}</h1>
<button onClick={this.changeNumber}>Increase number by 1</button>
</div>
)
}
}
class Child extends React.Component {
render() {
return(
<div>
<GrandChild number={this.props.number}/>
</div>
)
}
}
class App extends React.Component {
constructor() {
super()
this.state = {
number: 1
}
}
render() {
return (
<Child number={this.state.number}/>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
I did code this in CodePen for those who want to test the code: https://codepen.io/anon/pen/oEeQdr
I hope there's a simple solution for this.
Thanks in advance.
class GrandChild extends React.Component {
changeNumber=()=> {
this.props.changeNumber();//call parent `changeNumber` method
}
render() {
return(
<div>
<h1>The number is {this.props.number}</h1>
<button onClick={this.changeNumber}>Increase number by 1</button>
</div>
)
}
}
class Child extends React.Component {
render() {
return(
<div>
<GrandChild number={this.props.number} changeNumber={this.props.changeNumber} /> //passed `changeNumber` as it is to `GrandChild`
</div>
)
}
}
class App extends React.Component {
constructor() {
super()
this.state = {
number: 1
}
}
changeNumber=()=>{
this.setState((prevState)=>{
console.log(prevState);
return {
number : prevState.number + 1
}
});
}
render() {
return (
<Child number={this.state.number} changeNumber = {this.changeNumber}/> //passed `changeNumber` to Child
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Working codepen
Check working code below:
import React from 'react';
import ReactDOM from 'react-dom';
class GrandChild extends React.Component {
render() {
return (
<div>
<h1>The number is {this.props.number}</h1>
<button onClick={this.props.incNumber}>Increase number by 1</button>
</div>
);
}
}
class Child extends React.Component {
render() {
return (
<div>
<GrandChild number={this.props.number} incNumber={this.props.incNumber} />
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
number: 1
};
}
incrementNumber = () => {
this.setState({ number: this.state.number + 1 });
};
render() {
return (
<Child number={this.state.number} incNumber={this.incrementNumber} />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
You can send method body as a prop to Child Class, as a pointer to it, and when you wil lcal this method in the Child, it will properly executed in the Parent, where was declared.
class GrandChild extends React.Component {
render() {
return (
<div>
<h1>The number is {this.props.passedProps.number}</h1>
<button onClick={() =>
this.props.passedProps.increaseNumber()}>Increase number by 1</button>
</div>
);
}
}
class Child extends React.Component {
render() {
return (
<div>
<GrandChild passedProps={this.props}/>
</div>
);
}
}
class App extends React.Component {
constructor() {
super()
this.state = {
number: 1
}
}
increaseNumber = () => {
this.setState({ number: this.state.number + 1 });
}
render() {
return (
<Child number={this.state.number} increaseNumber={this.increaseNumber}/>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));

Search filter is not working in React.js

this is 1st component as index.jsx
this is array which contains all the data.
let details=[{
id:'1',
website: 'amazon',
username:'harry',
password: '1234'
},
{
id:'2',
website: 'flipkart',
username:'nowag',
password: 'gfjh'
},
{
id:'3',
website: 'skype',
username:'king',
password: 'yesyes'
},
{
id:'4',
website: 'facebook',
username:'deep',
password: 'hellohello'
}];
class app starts here
class App extends React.Component{
constructor(props) {
super(props);
this.state= {
filter: null
};
}
setFilter(filter) {
this.setState({filter: filter})
}
render(){
error is out here that "Cannot read property 'filter' of undefined"
let filteredPassword = this.props.details.filter(
(detail) =>{
return detail.website.toLowerCase().indexOf(this.state.search)!= -1;
}
);
return (
<ul>
<Filter onUpdateFilter={this.setFilter} />
{
filteredPassword.map((detail)=>{
return <Detail item={detail} key={detail.id} />
})}
</ul>
)
}
}
export default App;
now there is another component filter.jsx
class Filter extends React.Component{
constructor(props) {
super();
this.state= {
search:'Search'
};
}
updateSearch(event) {
this.setState({search: event.target.value.substr(0,40)});
//this.props.onUpdateFilter(event.target.value.substr(0,40))
}
render() {
return (
<div>
<input type="text" defaultValue={this.state.search} onchange={this.updateSearch.bind(this)}/>
</div>
)
}
}
this is way, which i tried to run my filter, but it is not working
This is what your code should look like :
class App extends React.Component{
constructor(props) {
super(props);
this.state= {
filter: null
};
this.setFilter = this.setFilter.bind(this);
}
setFilter(filter) {
this.setState({filter: filter})
}
render(){
let filteredPassword = this.props.details.filter(
(detail) =>{
return detail.website.toLowerCase().indexOf(this.state.search)!= -1;
}
);
return (
<ul>
<Filter onUpdateFilter={this.setFilter} />
{
filteredPassword.map((detail)=>{
return <Detail item={detail} key={detail.id} />
})}
</ul>
)
}
}
export default App;
class Filter extends React.Component{
constructor(props) {
super(props);
}
updateSearch(event) {
this.props.onUpdateFilter(event.target.value.substr(0,40))
}
render() {
return (
<div>
<input type="text" defaultValue="Search" onchange={this.updateSearch.bind(this)}/>
</div>
)
}
}
If you don't pass details to the component, you need replace this.props.details to details
And replace this, because setFilter has wrong context
<Filter onUpdateFilter={this.setFilter} />
to this:
<Filter onUpdateFilter={filter => this.setFilter(filter)} />
or bind in constructor:
constructor(props) {
super(props);
this.state= {
filter: null
};
this.setFilter = this.setFilter.bind(this)
}

Categories

Resources