1

So in short, I'm trying to use an array.map that can be called from one of two arrays depending on an if statement. A bit like so

class App extends Component { state = { foo: [ {number:"0"}, {number:"1"}, {number:"2"}, {number:"3"} ], bar: [ {number:"9"}, {number:"8"}, {number:"7"}, {number:"6"} ], fooBar: "foo" } test = () => { if(this.state.fooBar === "foo") { return this.state.foo } else { return this.state.bar } } onChangeFooBar = () = { this.setstate({fooBar: bar}) } render(){ <Button onClick={this.onChangeFooBar}>Set to bar</Button> <p>Here are some lines of text</p> {this.test.map(list => <p> {list.text} </p>)} } } 

However, it throws an error saying it's not a function. What is it I'm no getting here? I'm almost certain my issue is in the.test

1
  • As Kind User pointed out, don't forget to add the return statement inside your render method. Commented Nov 10, 2017 at 13:54

3 Answers 3

5

this.test is a function, not an array. Try to call it first:

{this.test().map(list => <p> {list.text} </p>)} 
Sign up to request clarification or add additional context in comments.

3 Comments

Unless I'm missing something it should be list.number, right?
Bingo. Not sure how I didn't think to do that bit. Thanks
@Chris You're correct there, I literally chucked that together in 5 mins in notepad++ for this post and missed that mistake.
1

You could as well skip test() function and instead write:

this.state[this.state.fooBar].map(list => <p> {list.number} </p>);

1 Comment

Great solution if this.state.fooBar takes the same value as the other state keys (either foo or bar).
0

Your render function doesn't return anything. Anyways, test function is redundant.

Suggested approach:

render(){ const { foo, bar, fooBar } = this.state; const r = fooBar === 'foo' ? foo : bar; return ( <Button onClick={this.onChangeFooBar}>Set to bar</Button> <p>Here are some lines of text</p> {r.map(({ number }) => <p>{number}</p>)} ) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.