2

I'm a bit new to reactJs, I have an array of notes I want to display in the component;

data: {
    title: 'notes for ABC', 
    notes: ['hello', 'world', 'blah blah]
}

When I try rendering this as data.notes.map it said data.notes.map is not a function. Any help!

0

1 Answer 1

7

I'm not sure exactly how you're planning on getting your data to your component but this example is how you could do it via the state. If you're having a specific component rendering a post or note, it would be better to do it via props. I would read the List and Keys docs for React.

Class Style

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
  constructor(props) {
    super(props); 
    this.state = { 
      notes: ['hello', 'world', 'blah blah'] 
    };
  }

  render() {
    const noteItems = this.state.notes.map((note) =>
      <li>{note}</li>
    );
    return (
      <ul>{noteItems}</ul>
    );
  }
}

export default App;

ReactDOM.render(<App />, document.getElementById('root'));

Functional Style

It seems like the functional way of writing this is more preferred, this is how you would write that.

import React, { useState } from 'react';

function App() {
  const [notes, setNotes] = useState(['hello', 'world', 'blah blah'])
  return <ul>{notes.map((note) => <li>{note}</li>)}</ul>
}

export default App;

ReactDOM.render(<App />, document.getElementById('root'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.