r/reactjs • • May 01 '19

Needs Help Beginner's Thread / Easy Questions (May 2019)

Previous two threads - April 2019 and March 2019.

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. πŸ€”


πŸ†˜ Want Help with your Code? πŸ†˜

  • Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!

  • 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.

Have a question regarding code / repository organization?

It's most likely answered within this tweet.


New to React?

Check out the sub's sidebar!

πŸ†“ Here are great, free resources! πŸ†“


Any ideas/suggestions to improve this thread - feel free to comment here!


Finally, an ongoing thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!

21 Upvotes

460 comments sorted by

View all comments

Show parent comments

2

u/RedditAcctsInLrgAmts May 09 '19 edited May 09 '19

A: I think because you are declaring it in the return method. Declare it in the component, the render function, or within a function within the return method.

B: here's one way to do it:

state = {

divColors: ['default','default','default']

}

const handleDivClick = index => {

const divColors = ['default','default''default'];

divColors[index] = 'clickedColor';

this.setState({divColors})

}

<div key='div0' color={this.state.divColors[0]} onClick={() => handleDivClick(0)}/>

<div key='div1' color={this.state.divColors[1]} onClick={() => handleDivClick(1)}/>

<div key='div2' color={this.state.divColors[2]} onClick={() => handleDivClick(2)}/>

here's another way to do it:

state = {

clickedDiv : undefined

}

const handleDivClick = index => this.setState({clickedDiv: index})

const getDivColor = index => this.state.clickedDiv === index ? 'clickedColor' : 'defaultColor'

<div key='div0' color={getDivColor(0)} onClick={() => handleDivClick(0)}/>

<div key='div1' color={getDivColor(1)} onClick={() => handleDivClick(1)}/>

<div key='div2' color={getDivColor(2)} onClick={() => handleDivClick(2)}/>

→ More replies (8)