Skip to content

Instantly share code, notes, and snippets.

@MwirabuaTimothy
Last active May 8, 2020 11:01
Show Gist options
  • Save MwirabuaTimothy/4e46dc2a5052e5ffb2c1e43513ddae8b to your computer and use it in GitHub Desktop.
Save MwirabuaTimothy/4e46dc2a5052e5ffb2c1e43513ddae8b to your computer and use it in GitHub Desktop.
Turning a class component to functional component
import React from "react"
import { connect } from "react-redux"
import { addItems } from "../../redux/actions/items"
const enhance = connect(
({ items }) => ({ items }),
{ addItems }
)
class ItemsList extends React.Component {
render() {
return (
<div>
<ul>
{this.props.items.map((item, index) => {
return (
<li key={index}>
{this.renderItem(item)}
</li>
)
})}
</ul>
<button onClick={this.onAddButtonClick}>Add Item</button>
</div>
)
}
renderItem = item => <div>{item}</div>
onAddButtonClick = e => {
const text = window.prompt("Enter item text:")
this.props.addItems(text)
}
}
export default enhance(ItemsList)
@abel-masila
Copy link

abel-masila commented May 8, 2020

import React from "react";
import { connect } from "react-redux";
 import { addItems } from "../../redux/actions/items"

const enhance = connect(({ items }) => ({ items }), { addItems });

const ItemsList = (props) => {
  renderItem = (item) => <div>{item}</div>;
  onAddButtonClick = (e) => {
    const text = window.prompt("Enter item text:");
    props.addItems(text);
  };
  return (
    <div>
      <ul>
        {props.items.map((item, index) => {
          return <li key={index}>{renderItem(item)}</li>;
        })}
      </ul>
      <button onClick={onAddButtonClick}>Add Item</button>
    </div>
  );
};
export default enhance(ItemsList)```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment