React.js The proper way to move content (text) to separate file from React Component?

Hi ; ),

I want to move const content to separate file index.jsx and map these elements (image, title, description, user, index) as I have below in my code.
What is the proper way to do this?
Thank you in advance.

import React from 'react'

import Slider from 'react-animated-slider'
import './style.css'

const content = [
  {
    title: 'Vulputate Mollis Ultricies Fermentum Parturient',
    description:
      'Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Cras justo odio, dapibus ac facilisis.',

    user: 'Luan Gjokaj',
    image: 'https://i.imgur.com/g7knisA.jpg',
  },
  {
    title: 'Tortor Dapibus Commodo Aenean Quam',
    description:
      'Nullam id dolor id nibh ultricies vehicula ut id elit. Cras mattis consectetur purus sit amet fermentum. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Donec sed odio dui.',

    user: 'Erich Behrens',
    image: 'https://i.imgur.com/z01nust.jpg',
  },
  {
    title: 'Phasellus volutpat metus',
    description:
      'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Duis mollis, est non commodo luctus, nisi erat porttitor ligula.',

    user: 'Bruno Vizovskyy',
    image: 'https://i.imgur.com/ATzVPxl.jpg',
  },
]

const RecommendationsSlider = () => (
  <div id="recommendation">
    <H1>Polecenia</H1>
        <Slider className="slider-wrapper">
          {content.map(({ image, title, description, user }, index) => (
            <div
              key={index}
              className="slider-content"
              style={{ background: `url('${image}')` }}
            >
              <div className="inner">
                <h1>{title}</h1>
                <p>{description}</p>
              </div>
              <section>
                    <span>
                    <strong>{user}</strong>
                    </span>
              </section>
            </div>
          ))}
        </Slider>
  </div>
)


export default RecommendationsSlider






This is fine. I wouldn’t use this everywhere so be careful of overuse, but I do things like this where appropriate.

Generally I would put the content in it’s own JS file (not .json because .json sucks) and import it. This way your component isn’t messy with data.

yourDataFile.js

export const content = [ ...stuff ]

yourComponent.jsx

import React from 'react'
import Slider from 'react-animated-slider'

import { content } from '../path/to/file/yourDataFile'
import './style.css'

const RecommendationsSlider = () => (
  <div id="recommendation">
    <H1>Polecenia</H1>
        <Slider className="slider-wrapper">
          {content.map(({ image, title, description, user }, index) => (
            <div
              key={index}
              className="slider-content"
              style={{ background: `url('${image}')` }}
            >
              <div className="inner">
                <h1>{title}</h1>
                <p>{description}</p>
              </div>
              <section>
                    <span>
                    <strong>{user}</strong>
                    </span>
              </section>
            </div>
          ))}
        </Slider>
  </div>
)


export default RecommendationsSlider
1 Like

Actually I wouldn’t bundle this with the app at all – you’d have to deploy your entire app each time you edit those recommendations, and clutter your commit history with content revisions. Instead you might fetch such content from a backend service, or maybe JSON files in your public directory:

class ContentContainer extends Component {
  state = {
    content: null,
    error: null
  }

  componentWillMount () {
    window.fetch(`${process.env.PUBLIC_URL}/content/content.json`)
      .then(response => {
        if (!response.ok) {
          throw new Error(`${response.status} ${response.statusText}`)
        }

        return response
      })
      .then(response => response.json())
      .then(content => this.setState({ content }))
      .catch(error => this.setState({ error }))
  }

  render () {
    const { error, content } = this.state

    return error
      ? <p>An error occurred: {error.message}</p>
      : !content
      ? <p>Loading...</p>
      : <RecommendationsSlider content={content}></RecommendationsSlider>
  }
}

That fetch functionality could then of course get abstracted away as a HOC or by taking a render prop to make it reusable for any content / component.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.