Cameron
Cameron

Reputation: 185

Refactor React.js code for style and efficiency

New to React.js.

My code is simple but there is a lot of repetition and hard coded numbers in the App.js file.

How would I get rid of redundancies? AND/OR How would I get rid of the hard coded numbers?

App.js

import React, { Component } from "react";
import Layout from "./components/Layout";
import one from "./components/img/one.jpg";
import two from "./components/img/two.jpg";
import three from "./components/img/three.jpg";

class App extends Component {
state = {
title: ["Monsoon III", "Beans", "Move 2"],
description:
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent at 
magna sed nunc venenatis congue nec non dui. Maecenas efficitur luctus 
tellus sed volutpat. Sed egestas tortor id erat sollicitudin, vehicula 
gravida nulla facilisis. Lorem ipsum dolor sit amet, consectetur 
adipiscing elit. Praesent in velit sem. Maecenas pellentesque 
scelerisque mauris, ac lobortis neque laoreet et. In tristique tellus 
sed ante venenatis fermentum. Mauris sed libero augue."
};

render() {
return (
  <div>
    <Layout
      type={true}
      img={one}
      title={this.state.title[0]}
      description={this.state.description}
    />
    <Layout
      type={false}
      img={two}
      title={this.state.title[1]}
      description={this.state.description}
    />
    <Layout
      type={true}
      img={three}
      title={this.state.title[2]}
      description={this.state.description}
    />
  </div>
);
}
}

export default App;

Layout.js

import React, { Component } from "react";

class layout extends Component {
layoutType() {
//if true return the first layout type
if (this.props.type) {
  return (
    <div>
      <img src={this.props.img} />
      <p>
        <h1>{this.props.title}</h1>
        {this.props.description}
      </p>
    </div>
  );
}
//else return the second layout type
return (
  <div>
    <p>
      <h1>{this.props.title}</h1>
      {this.props.description}
    </p>
    <img src={this.props.img} />
  </div>
);
}

render() {
return <div>{this.layoutType()}</div>;
}
}

export default layout;

Again,

How would I get rid of redundancies? AND/OR How would I get rid of the hard coded numbers?

Upvotes: 0

Views: 119

Answers (1)

Steven
Steven

Reputation: 71

I think the hard coded number can be refactored to list

render() {
  const { title, description } = this.state
  const imgs = [one, two, three]
  const Layouts = title.map((item,index) => {
    return (
      <Layout
        type={false}
        img={imgs[index]}
        title={item}
        description={description}
      />
    )
  })
  return Layouts
}

Upvotes: 2

Related Questions