Search code examples
javascriptreactjsrenderjsxcode-splitting

React - print content of imported component function


Trying to split some HTML chunks by dividing the HTML in smaller pieces, located in the components folder. (I know, HTML is not really html, it is JSX).

The outcome I am trying to achieve is to have the imported component [Navigation] to render its content.

I do understand that there might be tools for the code splitting.

Question: Why doesnt the code render the div navigation content?


Navigation.js

import React from 'react';

export default function Navigation() {
  return (
    <div className="navigation">
      <ul>
        <li>
          <a href="http://www.google.com">Google</a>
        </li>
      </ul>
    </div>
  );
}

App.js

import React from 'react';
import './App.css';
import Navigation from './components/Navigation';

class App extends React.Component {
  render() {
    Navigation();
    return (
      <div>
        Hello from component - Class!
      </div>
    );
  }
}

export default App;

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

Solution

  • Your component is not rendering because u call de function outside the return statement.

    For a component render, you need to return the component inside the render function;

    Example:

    render () {
      return <Component/>
    }
    

    When u call this:

    render() {
      Navigation(); // see, the navigation is outside the return statemente
      return (
        <div>
          <p>Hello from component - Class!</P>
        </div>
      )
    }
    

    try this:

    import React from 'react';
    import './App.css';
    import Navigation from './components/Navigation';
    class App extends React.Component {
     render() {
         return (
             <div>
               <Navigation/>
               <p>Hello from component - Class!</P>
             </div>
         )
     }
    }
    
    export default App;