I am attempting to abstract out functionality of a simple app based in ReactJS, however the console is throwing up a few problems that I can't figure out.
It seems to revolve around my use of this.setState(...)
I have commented out the original functions in the main Class just for visibility.
Button Class (will be moved to new file)
class Button extends React.Component {
buttonAction(props) {
switch (this.props.type) {
case 'add':
this.setState((prevState) => ({
counter: prevState + this.props.label
}));
break;
case 'take':
this.setState((prevState) => ({
counter: prevState - this.props.label
}));
break;
case 'reset':
this.setState(() => ({
counter: 0
}));
}
}
render() {
return (
<button onClick={this.buttonAction(this.props.type)}>{this.props.label}</button>
)
}
}
App class
class App extends React.Component {
// initial state of counter
state = {
counter: 0
};
// // function to increment the counter
// incrementCounter = (increment) => {
// this.setState((prevState) => ({
// counter: prevState.counter + 1
// }));
// };
render() {
return (
<div>
<Button type={'add'} label={1}/>
{this.state.counter}
</div>
)
}
}
const root = document.getElementById('root');
ReactDOM.render(<App />, root);
Please see my code example here
You are not calling buttonAction with the correct this context. You need to bind it to your component. Try adding this to your Button component:
constructor(props) {
super(props);
this.buttonAction = this.buttonAction.bind(this);
}
Edit:
The way of passing the event handler buttonAction is incorrect. This should be the correct way of doing it:
<button onClick={this.buttonAction}>{this.props.label}</button>
I managed to solve by looking at an older piece of code I already had...
#Jules Dupont was on the right track in his first answer, moving functions into the App class.
However, I decided to refactor a few things and have ended up with the following:
// Class of button to click
class Button extends React.Component {
// function to handle click
handleClick = () => {
this.props.onClickFunction(this.props.increment, this.props.type)
};
// what to render to virtual DOM
render() {
return (
<button
onClick={this.handleClick}>
{this.props.state}{this.props.increment}
</button>
);
}
}
// Result output
const Result = (props) => {
return (
<div>{props.counter}</div>
);
};
// App class
class App extends React.Component {
// initial state of counter
state = {
counter: 0
};
operators = {
'+': function (a, b) { return a + b },
'-': function (a, b) { return a - b },
// ...
};
// function to increment the counter
incrementCounter = (increment, type) => {
console.log('hit')
this.setState((prevState) => ({
counter: this.operators[type](prevState.counter,increment)
}));
};
// what to render to virtual DOM
render() {
return (
<div>
{/* Buttons of different incremental value */}
<Button type={'+'} increment={1} onClickFunction={this.incrementCounter} />
<Button type={'-'} increment={1} onClickFunction={this.incrementCounter} />
{/* result that will be displayed */}
<Result counter={this.state.counter} />
</div>
)
}
}
Related
I'm trying to change one value inside a nested state.
I have a state called toDoItems that is filled with data with componentDidMount
The issue is that changing the values work and I can check that with a console.log but when I go to setState and then console.log the values again it doesn't seem like anything has changed?
This is all of the code right now
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
toDoItems: null,
currentView: "AllGroup"
};
}
componentDidMount = () => {
fetch("/data.json")
.then(items => items.json())
.then(data => {
this.setState({
toDoItems: [...data],
});
})
};
changeToDoItemValue = (givenID, givenKey, givenValue) => {
console.log(this.state.toDoItems);
let newToDoItems = [...this.state.toDoItems];
let newToDoItem = { ...newToDoItems[givenID - 1] };
newToDoItem.completedAt = givenValue;
newToDoItems[givenID - 1] = newToDoItem;
console.log(newToDoItems);
this.setState({
toDoItems: {newToDoItems},
})
console.log(this.state.toDoItems);
};
render() {
if (this.state.toDoItems) {
// console.log(this.state.toDoItems[5 - 1]);
return (
<div>
{
this.state.currentView === "AllGroup" ?
<AllGroupView changeToDoItemValue={this.changeToDoItemValue}/> :
<SpecificGroupView />
}
</div>
)
}
return (null)
};
}
class AllGroupView extends Component {
render() {
return (
<div>
<h1 onClick={() => this.props.changeToDoItemValue(1 , "123", "NOW")}>Things To Do</h1>
<ul className="custom-bullet arrow">
</ul>
</div>
)
}
}
So with my console.log I can see this happening
console.log(this.state.toDoItems);
and then with console.log(newToDoItems)
and then again with console.log(this.state.toDoitems) after setState
State update in React is asynchronous, so you should not expect updated values in the next statement itself. Instead you can try something like(logging updated state in setState callback):
this.setState({
toDoItems: {newToDoItems},// also i doubt this statement as well, shouldn't it be like: toDoItems: newToDoItems ?
},()=>{
//callback from state update
console.log(this.state.toDoItems);
})
a react component that will display the current value of our counter.
The counter should start at 0.
There should be a button to add 1.
There should also be a button to subtract 1.
I am unable to understand the problem, as to what is it that I have missed or some wrong syntax.
const React = require('react');
class Counter extends React.Component{
constructor(...args){
super(...args);
this.state = { counter: 0 };
}
// Your event handlers
cincrement = () => {
this.setState({ counter: this.state.counter+1 });
};
cdecrement = () => {
this.setState({ counter: this.state.counter-1 });
};
render() {
return (
<div>
<h1>{this.state.counter}</h1>
<button type="button" onClick={this.cincrement}>
Decrement
</button>
<button type="button" onClick={this.cdecrement}>
Increment
</button>
</div>
)
}
}
The error that I get on running the code
/runner/node_modules/babel-core/lib/transformation/file/index.js:590
throw err;
^
SyntaxError: /home/codewarrior/index.js: Unexpected token (16:13) 14
| // Your event handlers 15 |
16 | cincrement = () => {
| ^ 17 | this.setState({ counter: this.state.counter+1 }); 18 | }; 19 |
at Parser.pp$5.raise (/runner/node_modules/babylon/lib/index.js:4454:13)
at Parser.pp.unexpected (/runner/node_modules/babylon/lib/index.js:1761:8)
at Parser.pp$1.parseClassProperty (/runner/node_modules/babylon/lib/index.js:2571:50)
at Parser.parseClassProperty (/runner/node_modules/babylon/lib/index.js:6157:20)
at Parser.pp$1.parseClassBody (/runner/node_modules/babylon/lib/index.js:2516:34)
at Parser.pp$1.parseClass (/runner/node_modules/babylon/lib/index.js:2406:8)
at Parser.pp$1.parseStatement (/runner/node_modules/babylon/lib/index.js:1843:19)
at Parser.parseStatement (/runner/node_modules/babylon/lib/index.js:5910:22)
at Parser.pp$1.parseBlockBody (/runner/node_modules/babylon/lib/index.js:2268:21)
at Parser.pp$1.parseBlock (/runner/node_modules/babylon/lib/index.js:2247:8)
It seems your babel config does not include class properties syntax
You could use normal prototype methods and then prebind them in constructor
Also since your next state depends on the prev state you should pass a callback to setState
const React = require('react');
class Counter extends React.Component{
constructor(...args){
super(...args);
this.state = { counter: 0 };
this.cincrement = this.cincrement.bind(this);
this.cdecrement= this.cdecrement.bind(this)
}
// Your event handlers
cincrement(){
this.setState(state => ({ counter: state.counter+1 }));
}
cdecrement() {
this.setState(state => ({ counter: state.counter-1 }));
}
render() {
return (
<div>
<h1>{this.state.counter}</h1>
<button type="button" onClick={this.cincrement}>
Decrement
</button>
<button type="button" onClick={this.cdecrement}>
Increment
</button>
</div>
)
}
}
React needs binding on event handlers.
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
One way to avoid this is to define the handlers inside the constructor:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = ev => {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
Your original code, IIRC, needs a special babel plugin to work.
I want to create a react component instance and render it in a static place programmatically.
My use-case is that I open a sequence of dialogs in an unknown length and when I get a response from a dialog I open the next.
I want to do something like:
const DialogExample = () => ({ question, onAnswer }) =>
(<div>
{question}
<button onClick={onAnswer}>answer</button>
</div>);
class SomeComponent extends React.Component {
async start() {
const questions = await getSomeDynamicQuestions();
this.ask(questions);
}
ask(questions) {
if (questions.length === 0) {
// DONE.. (do something here)
return;
}
const current = questions.pop();
React.magicMethod(
// The component I want to append:
<DialogExample
question={current}
onAnswer={() => this.ask(questions)}
/>,
// Where I want to append it:
document.getElementsByTagName('body')[0]);
}
render() {
return (
<div>
<button onClick={this.start}>start</button>
</div>);
}
}
I know that's not very "react-like", and I guess the "right" way of doing it will be storing those questions in state and iterate over them in "someComponent" (or other) render function, but still, I think that this pattern can make sense in my specific need.
Sounds like a case for Portals. I'd recommend doing something like this:
class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.body = document.getElementsByTagName('body')[0];
this.state = {
questions: [],
}
}
async start() {
const questions = await getSomeDynamicQuestions();
this.setState({ questions });
}
nextQuestion() {
this.setState(oldState => {
const [first, ...rest] = oldState.questions;
return { questions: rest };
})
}
render() {
const { questions } = this.state;
return (
<div>
<button onClick={this.start}>start</button>
{questions.length > 0 && ReactDOM.createPortal(
<DialogExample
question={questions[0]}
onAnswer={() => this.nextQuestion()}
/>,
this.body,
)}
</div>
);
}
}
I've read this post: React setState not Updating Immediately
and realized that setState is async and may require a second arg as a function to deal with the new state.
Now I have a checkbox
class CheckBox extends Component {
constructor() {
super();
this.state = {
isChecked: false,
checkedList: []
};
this.handleChecked = this.handleChecked.bind(this);
}
handleChecked () {
this.setState({isChecked: !this.state.isChecked}, this.props.handler(this.props.txt));
}
render () {
return (
<div>
<input type="checkbox" onChange={this.handleChecked} />
{` ${this.props.txt}`}
</div>
)
}
}
And is being used by another app
class AppList extends Component {
constructor() {
super();
this.state = {
checked: [],
apps: []
};
this.handleChecked = this.handleChecked.bind(this);
this.handleDeleteKey = this.handleDeleteKey.bind(this);
}
handleChecked(client_id) {
if (!this.state.checked.includes(client_id)) {
let new_apps = this.state.apps;
if (new_apps.includes(client_id)) {
new_apps = new_apps.filter(m => {
return (m !== client_id);
});
} else {
new_apps.push(client_id);
}
console.log('new apps', new_apps);
this.setState({apps: new_apps});
// this.setState({checked: [...checked_key, client_id]});
console.log(this.state);
}
}
render () {
const apps = this.props.apps.map((app) =>
<CheckBox key={app.client_id} txt={app.client_id} handler={this.handleChecked}/>
);
return (
<div>
<h4>Client Key List:</h4>
{this.props.apps.length > 0 ? <ul>{apps}</ul> : <p>No Key</p>}
</div>
);
}
}
So every time the checkbox status changes, I update the this.state.apps in AppList
when I console.log new_apps, everything works accordingly, but console.log(this.state) shows that the state is not updated immediately, which is expected. What I need to know is how I can ensure the state is updated when I need to do further actions (like register all these selected strings or something)
setState enables you to make a callback function after you set the state so you can get the real state
this.setState({stateYouWant}, () => console.log(this.state.stateYouWant))
in your case:
this.setState({apps: new_apps}, () => console.log(this.state))
The others have the right answer regarding the setState callback, but I would also suggest making CheckBox stateless and pass isChecked from MyApp as a prop. This way you're only keeping one record of whether the item is checked, and don't need to synchronise between the two.
Actually there shouldn't be two states keeping the same thing. Instead, the checkbox should be stateless, the state should only be kept at the AppList and then passed down:
const CheckBox = ({ text, checked, onChange }) =>
(<span><input type="checkbox" checked={checked} onChange={() => onChange(text)} />{text}</span>);
class AppList extends React.Component {
constructor() {
super();
this.state = {
apps: [
{name: "One", checked: false },
{ name: "Two", checked: false }
],
};
}
onChange(app) {
this.setState(
previous => ({
apps: previous.apps.map(({ name, checked }) => ({ name, checked: checked !== (name === app) })),
}),
() => console.log(this.state)
);
}
render() {
return <div>
{this.state.apps.map(({ name, checked }) => (<CheckBox text={name} checked={checked} onChange={this.onChange.bind(this)} />))}
</div>;
}
}
ReactDOM.render(<AppList />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
I try to map an array and put click event on the array items. I know it's a bit different because of how JavaScript handles functions but I can't make it work. I get the error: Cannot read property 'saveInStorage' of undefined. Can anyone tell me what I'm doing wrong? Thanks in advance! Here is my code:
import React from "react";
const data = require('../data.json');
export default class Gebruikers extends React.Component {
constructor() {
super();
this.state = {
users: data.users
};
this.saveInStorage = this.saveInStorage.bind(this)
}
saveInStorage(e){
console.log("test");
}
renderUser(user, i) {
return(
<p key={i} onClick={this.saveInStorage(user)}>f</p>
);
}
render() {
return (
<div>
{
this.state.users.map(this.renderUser)
}
</div>
);
}
}
this is undefined in renderUser()
You need to bind this for renderUser() in your constructor.
Also, you are calling saveInStorage() every time the component is rendered, not just onClick, so you'll need to use an arrow function in renderUser
import React from "react";
const data = require('../data.json');
export default class Gebruikers extends React.Component {
constructor() {
super();
this.state = {
users: data.users
};
this.saveInStorage = this.saveInStorage.bind(this);
this.renderUser = this.renderUser.bind(this);
}
saveInStorage(e){
console.log("test");
}
renderUser(user, i) {
return(
<p key={i} onClick={() => this.saveInStorage(user)}>
);
}
render() {
return (
<div>
{
this.state.users.map(this.renderUser)
}
</div>
);
}
}
Instead of binding you can also use an arrow function (per mersocarlin's answer). The only reason an arrow function will also work is because "An arrow function does not have its own this; the this value of the enclosing execution context is used" (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). The enclosing execution in your case is your render, where this is defined.
You need to make two changes to your code which are outlined below.
You are invoking the function when the component is rendered. To fix this update this line to the following
<p key={i} onClick={() => this.saveInStorage(user)}>
This means that the function will only be invoked when you click on the item.
You also need to bind the renderUser in your constructor or else use an arrow function.
this.renderUser = this.renderUser.bind(this);
See working example here.
Your onClick event handler is wrong.
Simply change it to:
onClick={() => this.saveInStorage(user)}
Don't forget to also bind renderUser in your constructor.
Alternatively, you can choose arrow function approach as they work the same as with bind:
class Gebruikers extends React.Component {
constructor(props) {
super(props)
this.state = {
users: [{ id: 1, name: 'user1' }, { id: 2, name: 'user2' }],
}
}
saveInStorage = (e) => {
alert("test")
}
renderUser = (user, i) => {
return(
<p key={i} onClick={() => this.saveInStorage(user)}>
{user.name}
</p>
)
}
render() {
return (
<div>{this.state.users.map(this.renderUser)}</div>
);
}
}
ReactDOM.render(
<Gebruikers />,
document.getElementById('root')
)
<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="root"></div>
Paul Fitzgeralds answer is the correct one, although I'd like to propose a different way of handling this, without all the binding issues.
import React from "react";
const data = require('../data.json');
export default class Gebruikers extends React.Component {
constructor() {
super();
this.state = {
users: data.users
};
}
saveInStorage = (e) => {
console.log("test");
};
render() {
return (
<div>
{this.state.users.map((user, i) => {
return (<p key={i} onClick={() => this.saveInStorage(user)}>f</p>);
})}
</div>
);
}
}
With saveInStorage = (e) => {}; you are binding the saveInStorage function to the this context of your class. When invoking saveInStorage you'll always have the (at least I guess so in this case) desired this context.
The renderUser function is basically redundant. If you return one line of JSX, you can easily do this inside your render function. I think it improves readability, since all your JSX is in one function.
You are not sending the parameters to this.renderUser
this.state.users.map((user, i) => this.renderUser(user, i))
Also your onClick function should be slightly changed. Here's the full code changed:
import React from "react";
const data = require('../data.json');
export default class Gebruikers extends React.Component {
constructor() {
super();
this.state = {
users: data.users
};
this.saveInStorage = this.saveInStorage.bind(this)
}
saveInStorage(e){
console.log("test");
}
renderUser(user, i) {
return(
<p key={i} onClick={() => this.saveInStorage(user)}>f</p>
);
}
render() {
return (
<div>
{
this.state.users.map((user, i) => this.renderUser(user, i))
}
</div>
);
}
}