Reputation: 197
Button is created in .map() does that make the button expire after the function ends? Cuz it apparently does not work.
Basically it reads from a JSON file storing an array, it loops through the array to display stuff including the button, which onClick should set the display to the article, but it got no response.
Here’s my code (I put comments on 2 places where stuff might go wrong but I’m not sure)
import React, {useState} from 'react';
import './App.css';
import content from './blogs.json';
function App() {
function mapper(arr){
return arr.map(item=>{
return (
<span>
{item}
</span>
);
});
}
function showArticle(id){ // HERE IS THE FUNCTION THAT IS CALLED WHEN BUTTON IS CLICKED, WHICH THERE SHOULD BE NO PROBLEM
setDisplay(1);
}
function createDisplay(arr) {
if(arr.length===0){
return <p>No articles found for this category</p>;
}else{
var out = [];
for(var i = 0; i<arr.length&&i<6;i++){
let item = arr[i];
let previewArticle = item.content;
if(previewArticle.length>200){
previewArticle = previewArticle.substr(0,199) + '...';
}
out.push(
(
<article class="preview" id={i}>
<h2>{item.title}</h2>
<p><small>{item.time}</small><br/>{previewArticle}</p>
<button onClick = {showArticle}>Read article</button> // HERE IS THE BUTTON THAT ISNT WORKING, DID IT EXPIRE AFTER THE FUNCTION?
</article>
)
);
}
return mapper(out);
}
}
function widthCheck(above, below) {
if(window.innerWidth>1000){
return above;
}else{
return below;
}
}
var contents = {
coding: [],
privacy: [],
editing: [],
minecraft: [],
main: [],
}
var [display, setDisplay] = useState(<p>Loading articles...</p>);
setTimeout(()=>{
display = createDisplay(content);
setDisplay(display);
}, 0)
return (
<div id="background">
<p>Choose a category or start reading below</p>
<ul id="content-nav">
<li onClick={()=>{}}>Privacy</li>
<li onClick={()=>{}}>Editing</li>
<li onClick={()=>{}}>Minecraft</li>
<li onClick={()=>{}}>Coding</li>
</ul>
{widthCheck([<br/>, <br/>, <br/>, <hr/>].map((item)=>{
return item;
}),<hr/>)}
<h1>Latest From Siriusmart</h1>
<div id="content">
{
display
}
</div>
</div>
);
}
export default App;
Upvotes: 0
Views: 239
Reputation: 2682
You are essentially hard-coding the display
to
{
coding: [],
privacy: [],
editing: [],
minecraft: [],
main: []
}
by doing this on every render:
setTimeout(()=>{
display = createDisplay(content);
setDisplay(display);
}, 0)
based on the code it is hard to see what it is you are trying to achieve, but this is why the application doesn't respond to the click.
Upvotes: 1