Home > Back-end >  ReactDOM only renders one element
ReactDOM only renders one element

Time:04-03

Im working on a react website and i want a slideshow as background. But either the slideshow or just the navbar gets rendered. What am i doing wrong? And I am using MUI. What am I doing wrong?

My index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import SearchAppBar from "./components/navBar/SearchBar";
import TitleText from "./components/titletext/titletext";
import App from "./components/site-background/site-background";




ReactDOM.render(<SearchAppBar />,document.getElementById("navbar"));
ReactDOM.render(<App />,document.getElementById("slideshow"));

My HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>


</head>
<body id="slideshow">


<div id = "navbar" />


<div id="logo" />


</body>
</html>

CodePudding user response:

You can return only one component. If you want to return multiple elements from a component use a wrapper div or React.Fragment.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import SearchAppBar from "./components/navBar/SearchBar";
import TitleText from "./components/titletext/titletext";
import App from "./components/site-background/site-background";




ReactDOM.render(
  <React.Fragment>
    <SearchAppBar />
    <App />
  </React.Fragment>
,document.getElementById("root"));

CodePudding user response:

Your HTML layout is such that the navbar is inside the slideshow:

<body id="slideshow">
  <div id = "navbar" />

So the navbar element gets removed from the DOM when React renders into the #slideshow element.

You probably wanted something like this instead:

<body>
  <div id="slideshow"></div>
  <div id = "navbar"></div>
  <div id="logo"></div>
</body>

(Don't use /> for normal tags in modern HTML - it's permitted in React, but not HTML5)

CodePudding user response:

When you render in this way only one element can be shown at once. You would need to make one render call and have div with both elements inside of it. You can also use a react.fragment instead of a div. It simply packages all of the items inside.

  • Related