React - User-Defined JSX Components Not rendering

3.1k views Asked by At

I've been trying to make an AJAX call and then add it to my view after it has been retrieved.

Nothing really happens with the current code.

const View = () => (
    <div>
     <h1>Reports</h1>
   <statisticsPage />
    </div>
);
export default View;


var statisticsPage = React.createClass({
  getInitialState: function() {
     return {info: "loading ... "};
  },
  componentDidMount: function() {
     this.requestStatistics(1);
  },
  render: function() {
    return (
        <div>info: {this.state.info}</div>
    );
  },
  requestStatistics:function(){
      axios.get('api/2/statistics')
      .then(res => {
        values = res['data']
        this.setState({info:1})
        console.log('works!!')
      });

    }

  })
1

There are 1 answers

0
Shubham Khatri On BEST ANSWER

You component name must begin with an Uppercase character since those beginning with lowercase are searched as default DOM elements like div, p, span etc. Which is not the case for your statisticsPage component. Make it uppercase and it works fine.

According to the docs:

When an element type starts with a lowercase letter, it refers to a built-in component like or and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.

We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.

const View = () => (
    <div>
     <h1>Reports</h1>
   <StatisticsPage />
    </div>
);



var StatisticsPage = React.createClass({
  getInitialState: function() {
     return {info: "loading ... "};
  },
  componentDidMount: function() {
     this.requestStatistics();
  },
  render: function() {
    return (
        <div>info: {this.state.info}</div>
    );
  },
  requestStatistics:function(){
        console.log('here');
        this.setState({info:1})
        console.log('works!!')
      

    }

  })

ReactDOM.render(<View/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>