Why is there no output when I try mapping an array? [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
So im creating a webpage that utilizes the REST Countries API. I have a useEffect that renders on the first run and store the data into a useState array but when I try mapping it in the body for some reason my ternary operator returns null saying that there is no data in my useState variable. Am I using the ternary operator right? I want to find out why my variable is null when there is clearly data in the variable
code:
const LightMode = () => {
const [data, setData] = useState([])
useEffect(() =>{
axios.get('https://restcountries.com/v3.1/all').then(res=>{
let toInsert = res.data.map((country) =>({
name: country.name.common,
population: country.population,
region: country.region,
capital: country.capital,
image: country.coatOfArms.png
}))
setData((prev) => [...prev, ...toInsert])
})
}, [])
console.log(data)
return(
<div>
<NavigationBar />
<div className='temp'>
{data ? data.map((country) =>{
<div>
country.name
</div>
}) : null}
</div>
</div>
)
}
export default LightMode;

You are not returning anything in your map. You either need to remove the {} or add a return statement. Here I replaced the {} with () to auto return your JSX. You will also want to add {} around the country.name to make that javascript.
return(
<div>
<NavigationBar />
<div className='temp'>
{data ? data.map((country) =>(
<div>
{country.name}
</div>
)) : null}
</div>
</div>
)

Related

How to add class onclick button [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 days ago.
Improve this question
In my app I need to add sidebar, for example you need to edit something and you'll do it in a sidebar. The problem is that I don't know how to do this.
I tried a lot of things but the idea is that by clicking on button I can't add class '-active' to my sidebar panel.
// src/app.js
function App() {
...
<div className="basic_layout__sidepanel">
<SidePanel></SidePanel>
</div>
...
// src/pages/Companies/Companies.js
function Companies() {
....
const actionButtons = () => {
return (
<React.Fragment>
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-info mr-2"
onClick={MyFunction}
></Button>
</React.Fragment>
);
};
So how to add '-active' class to "basic_layout__sidepanel" from app.js by clicking on button from companies.js
The steps to accomplish this are very simple through. But we have to keep track of somethings first. Let’s assume this is you component structure
function App () {
// some functions here…
return (
<>
<button></button>
<SidePanel />
</>
);
}
Change it to something like
import React from ‘React’
function App () {
const [active, setActive] = React.useState(false);
const handleClick = () => {
setActive(a => !a);
}
return (
<>
<button onClick={handleClick}></button>
<SidePanel active={active} />
</>
);
}

Parsing error: Unexpected token, expected "," in react js [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
import { React,Fragment } from 'react'
import classes from 'Modal.module.css';
const Backdrop = (props) = {
return <div className={classes.backdrop} />
};
const ModalOverlay = props = {
return (
<div className={classes.modal}>
<div className={classes.content}>{props.childern}</div>
</div>
);
};
const poratalElement = document.getElementById('overlays');
const Modal = (props) => {
return (
<Fragment>
{ReactDOM.createPortal(<Backdrop/>, poratalElement)}
{ReactDOM.createPortal(<ModalOverlay>{props.children}</ModalOverlay>, poratalElement)}
</Fragment>
)
}
export default Modal
Whythis error occur and what is the solution for this. I am trying to use the both the compontent backdrop and Modaloverlay in my main compontent Modal.

CKEditor data does not upload in firestore with TypeError: text is not a function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I keep on having this error with these codes:
TypeError: text is not a function
const [text, setText] = useState("");
handlesubmit:
const handleSubmit = (e) => {
e.preventDefault();
try {
const userRef = firestore.collection("announcement").doc();
const ref = userRef.set({
text,
});
text("");
console.log(" saved");
} catch (err) {
console.log(err);
}
};
inside the return of the functional component:
<form onSubmit={handleSubmit}>
<CKEditor
editor={ClassicEditor}
data={text}
onChange={(event, editor1) => {
const data = editor1.getData();
setText(data);
}}
/>
<br />
<br />
<ButtonForm type="submit">Submit</ButtonForm>
</form>
Use setText("") instead text(""); on handleSubmit

React - Which way is better to pass arguments to prop functions in an array of stateless components? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm refactorying my react components, and wondering which way to pass arguments to prop functions is cleaner and more readable between a parent component and an array of children components.
pass arguments in the child component
const ChildComponent = ({data, onButtonClick}) => {
return (
<div>
{data.name}
<button type="button" onClick={() => onButtonClick(data.id)}>Clcik</button>
</div>
);
};
const ParentComponent = () => {
const list = [{id: 'a', name: 'Apple'}, {id: 'b', name: 'Banana'}];
const recordId = (id) => {
console.log(id);
};
return (
list.map((item) => (
<ChildComponent key={item.id} data={item} onButtonClick={recordId} />
))
);
};
pass arguments in the parent component
const ChildComponent2 = ({data, onButtonClick}) => {
return (
<div>
{data.name}
<button type="button" onClick={onButtonClick}>Clcik</button>
</div>
);
};
const ParentComponent2 = () => {
const list = [{id: 'a', name: 'Apple'}, {id: 'b', name: 'Banana'}];
const recordId = (id) => {
console.log(id);
};
return (
list.map((item) => (
<ChildComponent2 key={item.id} data={item} onButtonClick={() => recordId(item.id)} />
))
);
};
The first way is better from optimization perspective because you can easily convert recordId into a stable entity (either by moving it outside of a component body since it's a pure function or using useCallback) so it won't trigger unnecessary rendering of the children (if you decide to use React.memo on them).
The second way is better from teamwork perspective. If another person takes care of ChildComponent he/she doesn't need to know anything about onClick handler coming from the parent because it's already assembled so all is there to do is to pass it on the button.

Cannot destructure property 'urls' of 'pin' as it is undefined [duplicate]

This question already has answers here:
JS/ES6: Destructuring of undefined
(8 answers)
Closed 1 year ago.
I have a small project, to fetch image from unsplash, even I check many times, I still have one problem in my code, I am running my code, but it is always give this error, but I don't get it. Any idea will be appreciated.
Mainboard.js
import React from 'react';
import styled from 'styled-components';
import Pin from './Pin';
function Mainboard(props) {
let { pins } = props;
return (
<Wrapper>
<Container>
{pins.map((pin, index) => {
let {urls} = pin;
return <Pin key={index} urls={urls}/>
})}
</Container>
</Wrapper>
)}
export default Mainboard;
Pin.js:
import React from 'react';
import styled from 'styled-components';
function Pin(props) {
let { urls } = props;
return (
<Wrapper>
<Container>
<img src={urls?.regular} alt="pin"/>
</Container>
</Wrapper>
)}
export default Pin;
I don't think the main issue is destructing from an undefined object (this is only a symptom), but more that you have "holes" in your data, i.e. your array has undefined elements in it.
If there is an undefined element in your pins array then perhaps you should filter them first before mapping. A quick way is to apply a Boolean constructor against the truthy defined values and the falsey undefined values, i.e. arr.filter(Boolean).
function Mainboard({ pins }) {
return (
<Wrapper>
<Container>
{pins.filter(Boolean).map((pin, index) => {
const {urls} = pin;
return <Pin key={index} urls={urls}/>
})}
</Container>
</Wrapper>
);
}
Of course you should try to ensure your data array is properly maintained in the first place so "holes" aren't introduced. If you add how Mainboard is rendered, what the props values are that are passed to it we may be better able to help optimize.

Categories

Resources