I have facing an issue in React JS. I want to show full name data separately.
Array of Object
0: {id: "1", wp_user_id: null, facebook_id: null, group_id: null, full_name: "furqan", …}
1: {id: "3", wp_user_id: null, facebook_id: null, group_id: null, full_name: "hassan",..}
My Code:
this.state = {
cusomterdata:[],
}
}
render() {
return (
<div>
{this.state.cusomterdata.map(function(item, i){
return ([
<p key={i}>{item.full_name}</p>,
<p key={i}>{item.id}</p>,
]);
})}
<div>
)
}
When i run this code Result here, They both come together
- furqan
- 1
- hassan
- 3
I want to do like this but it is not working.
<p key={i}>{item.full_name[0]}</p>, //just show first fullname
Expected Output
What should i do? Can anyone help me?
As far as I have understood, you just want to show the full_name only from the first item.
You may do the following:
render() {
let FullName = null;
if (this.state.cusomterdata) {
FullName = (
{
this.state.cusomterdata.map((data, index) => {
return (
<p key={index}>{data.full_name}</p>
)
})
}
)
}
return (
<div>
{ FullName }
</div>
)
}
Related
I receive an array like this from backend:
[
{
id: 0,
name: "John",
language: "Enlgish"
},
{
id: 1,
name: "Chris",
language: "Spanish"
},
{
id: 2,
name: "Bastian",
language: "German"
}
]
So I display the languages from this array in a table, and to do that I map through them.
I don't want to show the first language on the first object of this array
Parent.js
const [language, setLanguage] = useState ([])
useEffect(() => {
axios
.get('api').then((res) => {setLanguage(response.data.languages)})
}, [])
Child.js
return(
{language.map((lang, i) => {
return (
<tr key={"item-" + i}>
<td>
<div>
<input
type="text"
value={
lang.language
? lang.language.shift()
: lang.language
}
</div>
</td>
</tr>
))}
)
So what I have tried by far is the shift method which removes the first item of an array, but it didn't work.
This error happened :TypeError: lang.language.shift is not a function
How can I fix this?
Use the index
{language.map((lang, i) => {
(i > 0) && (
return (
......
During the React.js course I'm doing, I was tasked with making a simple fortune-teller app. Theoretically, everything works as planned, but I did the task differently than the tutor. Instead of a simple fortune-telling table, I've created an array of objects, each with its id and 'omen'. The problem arose when after adding a new 'omen' an alert should be displayed that gives the current content of 'omens' in state. Only the previous values appear, without the added value. I will be grateful for the hints. In the original design, this problem does not occur, although it is very similar.
class Draw extends React.Component {
state = {
index: "",
value: "",
omens: [
{ id: 1, omen: "Hard work pays off" },
{ id: 2, omen: "You will be rich" },
{ id: 3, omen: "Be kind to others" },
],
};
handleDrawOmen = () => {
const index = Math.floor(Math.random() * this.state.omens.length + 1);
this.setState({
index: index,
});
};
showOmen = () => {
let omens = this.state.omens;
omens = omens.filter((omen) => omen.id === this.state.index);
return omens.map((omen) => (
<h1 id={omen.id} key={omen.id}>
{omen.omen}
</h1>
));
};
handleInputChange = (e) => {
this.setState({
value: e.target.value,
});
};
handleAddOmen = () => {
if (this.state.value === "") {
return alert("Enter some omen!");
}
const omens = this.state.omens.concat({
id: this.state.omens.length + 1,
omen: this.state.value,
});
this.setState({
omens,
value: "",
});
console.log(this.state.omens);
alert(
`Omen added. Actual omens: ${this.state.omens.map(
(omen) => omen.omen
)}`
);
};
render() {
return (
<div>
<button onClick={this.handleDrawOmen}>Show omen</button>
<br />
<input
placeholder="Write your own omen..."
value={this.state.value}
onChange={this.handleInputChange}
/>
<button onClick={this.handleAddOmen}>Add omen</button>
{this.showOmen()}
</div>
);
}
}
ReactDOM.render(<Draw />, document.getElementById("root"));
The state object is immutable. So you need to create your new array and apply it afterwards:
const omens = [
...this.state.omens,
{
id: this.state.omens.length + 1,
omen: this.state.value,
}
]
also setState is async so you need to wait until it finished:
this.setState({
omens,
value: "",
}, () => {
alert(
`Omen added. Actual omens: ${this.state.omens.map(
(omen) => omen.omen
)}`
)
https://reactjs.org/docs/react-component.html#setstate
const rowData = this.state.market.map((market) => {
console.log("details", market["info"])
{
return {
marketInfo: (
<div>
{market && !!market["info"] ? (
<div>
<p>{market["info"]["name"]}</p>
</div>
) : null}
</div>
),
place: "place",
area: "area",
action: "action",
};
}
});
I am iterating an array in marketInfo, but I am getting the same name whenever i m iterating, but in console log I am getting different names. Whats actually wrong with my code! can anyone help me with it!
const rowData = this.state.market.map((market) => {
console.log("details", market["info"])
return {
marketInfo: (
<div>
{market?.["info"] ? (
<div>
<p>{market["info"]?.["name"] || ""}</p>
</div>
) : null}
</div>
),
place: "place",
area: "area",
action: "action",
};
});
try this code.
I think you forgot to return an object in your map func
In the following line:
checked={this.state.peopleChecked.some(({ asset}) => asset['object'] ['user']['id'] === person.userCompetences.map((user, index) => {
user['asset']['id']
})
)}
I have a problem comparing two objects.
Compares a property from the array people ->userCompetences -> asset ->id with an object from the array peopleChecked ->asset -> object ->user - > asset_id.
if id from arraypeople and asset_id, id === asset_id are equal to returnstrue. Checkbox is checked
Code here: https://stackblitz.com/edit/react-n2zkjk
class App extends Component {
constructor() {
super();
this.state = {
people: [
{
firstname: "Paul",
userCompetences: [
{ asset:{
id: "12345"
}
}
]
},
{
firstname: "Victor",
userCompetences: [
{ asset: {
id: "5646535"
}
}
]
},
{
firstname: "Martin",
userCompetences: [
{ asset: {
id: "097867575675"
}
}
]
},
{
firstname: "Gregor",
userCompetences: [
{ asset: {
id: "67890"
}
}
]
}
],
peopleChecked: [
{
amount: 0,
asset: {
id: "fgfgfgfg",
object: {
competence: null,
id: "dsdsdsdsd",
user: {
firstname: "Gregor",
asset_id: "67890"
}
}
}
},
{
amount: 0,
asset: {
id: "dsdsdsd",
object: {
competence: null,
id: "wewewe",
user: {
firstname: "Paul",
asset_id: "12345"
}
}
}
},
],
selectPeopleId: []
}
}
/*handleSelect = (person) => {
//Check if clicked checkbox is already selected
var found = this.state.peopleChecked.find((element) => {
return element.id == person.id;
});
if(found){
//If clicked checkbox already selected then remove that from peopleChecked array
this.setState({
peopleChecked: this.state.peopleChecked.filter(element => element.id !== person.id),
selectPeopleId: this.state.selectPeopleId.filter(element => element !== person.id)
}, () => console.log(this.state.peopleChecked))
}else{
//If clicked checkbox is not already selected then add that in peopleChecked array
this.setState({
selectPeopleId: [...this.state.selectPeopleId, person.id],
peopleChecked: [...this.state.peopleChecked,person]
}, () => {console.log(this.state.selectPeopleId);console.log(this.state.peopleChecked);})
}
}*/
render() {
return (
<div>
{this.state.people.map(person => (
<div key={person.id} className="mb-1">
<input
type={'checkbox'}
id={person.id}
label={person.firstname}
checked={this.state.peopleChecked.some(({ asset}) => asset['object']['user']['id'] === person.userCompetences.map((user, index) => {
user['asset']['id']
})
)}
onChange = {() => this.handleSelect(person)}
/> {person.firstname}
</div>
))}
</div>
);
}
}
Your correct checked code syntax would be below based on your data structure:
Issue was asset_id correct key was missing and map returns an array thus you would need its index, however in your case you can simply swap it with person.userCompetences.[0]['asset']['id'] but I kept your syntax in case you want it for some other purpose.
checked={
this.state.peopleChecked.some(
({ asset }) => asset['object']['user']['asset_id'] === person.userCompetences.map(
(user, index) => user['asset']['id']
)[0]
)}
However its inherently complicated and you should focus on untangling it by placing some cached const in your map function to keep track of what you are looking at. I would also advice to introduce some child component to render in the first map to make your life easier maintaining this code in the future.
Edited code: https://stackblitz.com/edit/react-ptsnbc?file=index.js
I'm trying to fetch data from my local json file.
Fetching the data don't give errors and everything is returning correctly in a console log.
When I try to set that data into a state, it works if I parse json and not json.data.
json.data don't do anything, but json works, only if I use the map function it gives me a bunch of errors
Code :
getData = () => {
fetch('http://localhost:3000/ingredients.json')
.then(response => {
if (response.ok) {
return response;
} else {
let response = `${response.statusText}`
let errorMessage = `${response.status(response)}`
let error = new Error(errorMessage)
throw (error)
}
})
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({ data: json })
console.log(this.state)
});
}
render() {
return (
<div>
{
this.state.data &&
this.state.data.map((key, display, nutrition) =>
<div key={key}>
{display}
{nutrition}
</div>
)}
</div>
)
}
Here are my error :
Objects are not valid as a React child (found: object with keys {key, display, unity, category, nutrition, vitamins}). If you meant to render a collection of children, use an array instead.
The map function of Array.prototype accepts a function callback with args, (value, index) => {}. If you plan is to destructure, use instead
this.state.data.map({key, display, nutrition, ...rest}, index) => { // index of value in this.sta
<div key={key}>
{display} //I am assuming this is a string not a object or array
{nutrition} // this should be a string
</div>
}
Edit:
I am assuming data is like
data: [
{
key: "",
nutrition: "",
display: ""
},
{
key: "",
nutrition: "",
display: ""
}
]
Edit 2:
Given this
state {
data =
[
{ id: 1,
display: 'Pommes',
unity: [ 'unités' ],
category: [ 'fruits' ],
nutrition: 95,
vitamins: [ 'C', 'B-6' ]
},
{
id: 2,
display: 'Poires',
unity: [ 'unités' ],
category: [ 'fruits' ],
nutrition: 95,
vitamins: [ 'C', 'B', 'E' ]
}
];
}
Here is how to display it:
render() {
return (
<>
{
this.state.data && this.state.data.map(({id, display, nutrition, vitamins}) => {
return (
<div key={id}>
{display}
{nutrition}
{<>vitamins.map(v => v) </>} //in case you need thing such as vitamis, Array, also to eppear
</div>
)})
}
</>
)
}
If your data is not array don't use map function. Change your code like below:
render() {
return (
<div>
{
this.state.data &&
<div key={this.state.data.key}>
{this.state.data.display}
{this.state.data.nutrition}
</div>
}
</div>
)
}