r/reactjs • u/swyx • Jul 01 '18
Help Beginner's Thread / Easy Question (July 2018)
Hello! just helping out /u/acemarke to post a beginner's thread for July! we had almost 550 Q's and A's in last month's thread! That's 100% month on month growth! we should raise venture capital! /s
Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch. No question is too simple. You are guaranteed a response here!
New to React? Free, quality resources here
Read the new, official Getting Started page on the docs
/u/acemarke's suggested resources for learning React and his React/Redux links list.
Want Help on Code?
Improve your chances of getting helped by putting a minimal example on to either JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new). Describe what you want it to do, and things you've tried. Don't just post big blocks of code.
If you got helped, pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.
4
u/swyx Jul 04 '18
hey!
no you are not bad at React. you just missed a minor but important detail: function binding.
thisin javascript catches people offguard a lot. its actually such a problem that React may move off of class based components one day because so many people run into it. you aren't alone.when you run
changeStateTest() {this.setState({testState: "It does work!!"});}, javascript doesnt actually know what thatthisrefers to. because you havent bound it to theAppclass. try it, try to addconsole.log(this)in there and you'll seeundefined.The docs offer 3 ways of binding your function, depending on your needs/babel setup. if you are working within a
create-react-app, then you have access to the "class properties transform". this means that you can change this:changeStateTest() {this.setState({testState: "It does work!!"});}to this:
changeStateTest = () => {this.setState({testState: "It does work!!"});}and it should work. thats my favorite method.
read the docs tho. this is one of those things you want to spend a bit of time understanding so that you never get tripped up by it ever again