HeathenINedeN
HeathenINedeN

Reputation: 123

How do I convert this class based component to a stateless component?

I am trying to render a table but I do not want to use a class based component.

How do I convert the following code into a const?

export default class Table extends Component {
    renderRow() {
        return (
            <View style={{ flex: 1, alignSelf: 'stretch', flexDirection: 'row' }}>
                <View style={{ flex: 1, alignSelf: 'stretch' }} /> { /* Edit these as they are your cells. You may even take parameters to display different data / react elements etc. */}
                <View style={{ flex: 1, alignSelf: 'stretch' }} />
                <View style={{ flex: 1, alignSelf: 'stretch' }} />
                <View style={{ flex: 1, alignSelf: 'stretch' }} />
                <View style={{ flex: 1, alignSelf: 'stretch' }} />
            </View>
        );
    }

    render() {
        const data = [1, 2, 3, 4, 5];
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            {
                data.map((datum) => { // This will render a row for each data element.
                    return this.renderRow();
                })
            }
            </View>
        );
    }
}

Upvotes: 0

Views: 17

Answers (1)

mainak
mainak

Reputation: 2301

This will be your functional component...

const Table = () => {
  const data = [1, 2, 3, 4, 5];

  const RenderRow = () => (
    <View style={{ flex: 1, alignSelf: "stretch", flexDirection: "row" }}>
      <View style={{ flex: 1, alignSelf: "stretch" }} />{" "}
      {/* Edit these as they are your cells. You may even take parameters to display different data / react elements etc. */}
      <View style={{ flex: 1, alignSelf: "stretch" }} />
      <View style={{ flex: 1, alignSelf: "stretch" }} />
      <View style={{ flex: 1, alignSelf: "stretch" }} />
      <View style={{ flex: 1, alignSelf: "stretch" }} />
    </View>
  );
  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      {data.map((datum,index) => (
        <RenderRow key={index}/>
      ))}
    </View>
  );
};

export default Table;

Upvotes: 1

Related Questions