I am trying to render a list of Folders in React using the GET function in JQuery. This is my code:
function HorizontalNav() {
return (
<nav className="navbar navbar-expand-lg">
<div className="container-fluid">
<div className="navbar navbar-collapse">
<ul className="navbar-nav me-auto">
<li className="nav-item me-3">
<a className=""><i className="bi bi-gear-fill"></i></a>
</li>
<li className="nav-item dropdown">
<a className="dropdown-toggle"><i className="bi bi-paint-bucket"></i></a>
</li>
</ul>
</div>
</div>
</nav>
);
}
function FolderList() {
var m = [];
$.get('get_folders', function(data) {
for (let x of data.folders) {
m.push(x);
}
});
return <ul>{m.map((y) => { return <li>{y.name}</li>; })}</ul>;
}
function App() {
return (
<div className="p-5">
<HorizontalNav/>
<div className="mt-3" id="folders">
<FolderList/>
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
Every time I load the page, nothing happens. All I see is the HorizontalNav and not the list of Folders. FYI I'm using Flask on the backend, and the above code is JSX.
CodePudding user response:
You should check out the State and Lifecycle topic in the React documentation.
To get and save the data on initialization, I recommend the useEffect
and useState
hooks.
The useEffect
hook corresponds to react's combined lifecycle methods componentDidMount
, componentDidUpdate
and componentWillUnmount
.
With useState
the data can be saved in the local state. Appropriate getters and setters are provided for this purpose.
function HorizontalNav() {
return (
<nav className="navbar navbar-expand-lg">
<div className="container-fluid">
<div className="navbar navbar-collapse">
<ul className="navbar-nav me-auto">
<li className="nav-item me-3">
<a className=""><i className="bi bi-gear-fill"></i></a>
</li>
<li className="nav-item dropdown">
<a className="dropdown-toggle"><i className="bi bi-paint-bucket"></i></a>
</li>
</ul>
</div>
</div>
</nav>
);
}
const { useState, useEffect } = React;
function FolderList() {
const [folders, setFolders] = useState([]);
useEffect(() => {
$.get('/folders', function(data) { setFolders(data.folders) });
}, []);
return (
<ul>{folders.map((x, i) => { return <li key={i}>{x.name}</li> })}</ul>
);
}
function App() {
return (
<div className="p-5">
<HorizontalNav/>
<div className="mt-3" id="folders">
<FolderList />
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);