React Task

by dzenkovich

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

ol {
  margin-left: 10px;
}

h3 {
  margin-bottom: 10px;
}

ul > li {
  margin-top: 10px;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

React

const authors = [
    {author: 'Nikolai Gogol', title: 'Taras Bulba'},
  	{author: 'Alexander Pushkin', title: 'I Loved You'},
    {author: 'Mikhail Lermontov', title: 'The Circassians'},
    {author: 'Alexander Pushkin', title: 'Ruslan and Ludmila'},
    {author: 'Mikhail Lermontov', title: 'Arbenin'},
    {author: 'Nikolai Gogol', title: 'Dead Souls'},
    {author: 'Alexander Pushkin', title: 'Poltava'},
    {author: 'Nikolai Gogol', title: 'The Nose'},
    {author: 'Mikhail Lermontov', title: 'Azrail'},
  ];
  
getBooks = function(){
	const out = authors.reduce((a, item) => {
  	const items = a[item.author] ? [...a[item.author], item.title] : [item.title];
  	return {
    	...a,
      [item.author]: items
    }
  }, {});
  
  return out;
}

class TodoApp extends React.Component {
	constructor(props){
  	super(props);
    this.state = {books: {}}
  }
  
  componentDidMount(){
  	this.setState({ books: getBooks()});
  };

  render() {
  	const { books } = this.state;
    
    return (
      <div>
        <h2>Books by Author</h2>
        {Object.keys(books).sort().map(author => {
        	const bookList = books[author];
          return (
          	<div>
            <h3><b>{author}</b></h3>
            <ol>
              {bookList.map(oneBook => (<li>{oneBook}</li>))}
            </ol>
            <br />
            </div>
            );
        })}
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))