STOPIMACODER
STOPIMACODER

Reputation: 822

How to render multiple components in react?

I'm trying to learn react and having problem with a small area. So this is my App.js :

import React from 'react';
import logo from './logo.svg';
import './App.css';

class App extends React.Component{
  render(){
    return <h1>Heyy</h1>;
  }
  render(){
    return <h1>Helo</h1>
  }
}

export default App;

It only renders the Helo. If i have multiple components lets say NavBar and ImageComp, how would i render it on single page with before passing it to ReactDOM.render?

From what i understand, every components goes into App before going into index.js but then how would i include multiple components in App?

Upvotes: 0

Views: 687

Answers (3)

Adrian
Adrian

Reputation: 1

This looks ok, I'm newbie

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

var element = React.createElement
(
  'h1', 
  { className: 'greeting' }, 
  'Hello, world2!'
);

var buttonelem = React.createElement
(
  'button', 
  { className: 'button-class' }, 
  'Cicker'
);


ReactDOM.render([element,buttonelem], document.getElementById('root'));

reportWebVitals();

Upvotes: 0

A. Horst
A. Horst

Reputation: 88

React also permits you to return an Array of elements.

class App extends Component{
  render(){
     return[          
           <h1>Title</h1>,
           <h2> Subtitle </h2>,
           <MyCustomComponent />
     ]
  }
}

Upvotes: 0

Dupocas
Dupocas

Reputation: 21297

A Component MUST return either JSX or nothing null. Everything you need to render from a class based component should go inside render method:

class App extends Component{
    render(){
         return(
           <>
               <h1>Title</h1>
               <h2> Subtitle </h2>
               <MyCustomComponent />
           </>
        )
    }
}

The notation <> </> it's just a shortcut to <React.Fragment /> to avoid returning adjacent JSX blocks

Upvotes: 4

Related Questions