Joe C
Joe C

Reputation: 1855

ReactJS - issue with rendering the proper component

I am pulling in a json response from the server. The json is an array of articles. Based on whether the article.id is even or odd it gets placed in the proper component.

If the article's id is an even number put the object in the LeftLargeImageArticle component, else put it in the LargeRightImageArticle component.

Console logging shows that the articles are put into the proper components, but when the page is rendered, it shows

JSON:

[
    {
      "image": "test1.jpg",
      "h4": "h4 title",
      "h3": "h3 title",
      "p": "foo bar baz.",
      "id": 1
    },
{
      "image": "test2.jpg",
      "h4": "h4 title",
      "h3": "h3 title",
      "p": "foo bar baz.",
      "id": 2
    },
{
      "image": "test3.jpg",
      "h4": "h4 title",
      "h3": "h3 title",
      "p": "foo bar baz.",
      "id": 3
    },
{
      "image": "test4.jpg",
      "h4": "h4 title",
      "h3": "h3 title",
      "p": "foo bar baz.",
      "id": 4
    }
]

React Parent Component:

var React = require('react');
var ScrollWrapper = require('./reusable-tool-components/ScrollWrapper.react');
var LargeLeftImageArticle = require('./reusable-tool-components/LargeLeftImageArticle.react');
var LargeRightImageArticle = require('./reusable-tool-components/LargeRightImageArticle.react');
var GuidingPrinciplesStore = require('./../stores/GuidingPrinciplesStore');


if (process.env.APP_ENV === 'browser') {
    var GuidingPrinciplesArticlesWebUtilsAPI = require('./../../utils/GuidingPrinciplesArticlesWebUtilsAPI');
    var test = GuidingPrinciplesArticlesWebUtilsAPI.initializeArticles();
    console.log("test: ", test);
}

var GuidingPrinciples = React.createClass({

  handleScroll: function(event) {
    console.log("GuidingPrinciples Component handleScroll");
  },

  getInitialState: function() {
    return {
      articles: GuidingPrinciplesStore.getArticles()
    };
  },

  render: function() {
    // I got them, but need to divide them up to place in the specific component
    var articleNodes = this.state.articles.map(function(article){
      if (article.id % 2 === 0) {
        console.log("put in left: ", article.id);
        return (
          <LargeLeftImageArticle h3={article.h3} h4={article.h4} p={article.p} image={article.image} key={article.id} />
        );
      } else {
        console.log("put in right: ", article.id);
        return (
          <LargeRightImageArticle h3={article.h3} h4={article.h4} p={article.p} image={article.image} key={article.id} />
        )
      }
    });
    console.log("articleNodes: ", articleNodes); /* Shows each article object as typeof react.element. */
    return (
      <div>
        <ScrollWrapper>
        <div className="product">
            <section className="container-fluid">
              <img src="images/gator.jpg" className="img-responsive" />
            </section>

            <section className="container">
              /* 
               * Currently on page rendering: article 1 (left large), 1 (right large), 3 (left large), 1 (right large). 
               * I need it to render: article 1 (right large), article 2 (left large), article 3 (right large), article 4 (left large). 
               * Why is this happening? Why don't the articles get rendered in the proper order? Are they being over-written? 
              */
              {articleNodes} 
            </section>
          </div>
        </ScrollWrapper>
      </div>
    )
  }
});

module.exports = GuidingPrinciples;

Child Component that should have the respective props based on if article id is even:

var React = require('react');

var LargeLeftImageArticle = React.createClass({
  render: function() {
    return (
      <article className="row large-left-img-article">
        <div className="col-md-6">
          <img src={"../images/" + this.props.image} alt={this.props.h3} className="img-responsive" />
        </div>
        <div className="col-md-6 content">
          <header>
            <h4>{this.props.h4}</h4>
            <h3>{this.props.h3}</h3>
          </header>
          <p>{this.props.p}</p>
        </div>
      </article>
    );
  }
});

module.exports = LargeLeftImageArticle;

Child component that should contain articles with odd ids:

var React = require('react');

var LargeRightImageArticle = React.createClass({
  render: function() {
    return (
      <article className="row large-right-img-article">
        <div className="col-md-6 content">
          <header>
            <h4>{this.props.h4}</h4>
            <h3>{this.props.h3}</h3>
          </header>
          <p>{this.props.p}</p>
        </div>
        <div className="col-md-6">
          <img src={"../images/" + this.props.image} alt={this.props.h3} className="img-responsive" />
        </div>
      </article>
    );
  }
});

module.exports = LargeRightImageArticle;

Upvotes: 1

Views: 53

Answers (1)

The Reason
The Reason

Reputation: 7973

I've created worked example for you i hope it will help you. So:

simple css

.left{
  width: 100px;
  height: 100px;
  float: left;
  background: red;
}

.right{
  width: 100px;
  height: 100px;
  float: right;
  background: green;
}

JSX file

class Left extends React.Component {
  constructor(props){
    super(props)
  }
  render() {
    const items = this.props.left.map((item)=>{
      return <li>{item}</li>
    })
    return <ul className="left">{items}</ul>
  }
}

class Right extends React.Component {
  constructor(props){
    super(props)
  }
  render() {
    const items = this.props.right.map((item)=>{
      return <li>{item}</li>
    })
    return <ul className="right">{items}</ul>
  }
}

class Main extends React.Component {
  constructor(){
    this.state = {
      count : 0,
      rightElements: [],
      leftElements: []
    }

    this.increment = this.increment.bind(this)
  }
  increment(){
    const newCount = this.state.count + 1,
                right = this.state.rightElements,
                left = this.state.leftElements;
    newCount % 2 === 0 ? right.push(newCount) : left.push(newCount)

    this.setState({
      count: newCount,
      rightElements: right,
      leftElements: left,
    });
  }
  render() {    
    return <div>
      <Right right={this.state.rightElements}/>
      <Left left={this.state.leftElements}/>
      <button onClick={this.increment}>Click Me</button>
    </div>
    }
 }


React.render(<Main/>, document.getElementById('container'));

Fiddle

Thanks

Upvotes: 1

Related Questions