this is my code in react.
const [value, setValue] = React.useState<CountriesEntityData | null>({
id: '',
name: '',
regions: [
{
id: '',
name: '',
districts: [
{
id: '',
name: '',
locations: [{ id: '', city: '', division: '', street: '' }],
},
],
},
],
})
I try this code in resolving this problem
value?.regions?.name
can anyone give me tutorial link in dealing in this kind of situation thank you.
If you just wanna use the first element you can do:
let name = value?.regions?.[0]?.name;
If if you wanna search the object based on an id, then I think there is a find function on the array which you can use like that:
let name = value?.regions?.find((elm) => elm.id == 'myId')?.name;
a regions in value is array.
and not answer value?.regions?.name .
because regions contains objects and objects contain property ```name'''
for this kind of problems, simply you can use log and see your variable in console
console.log(your const);
then by looking at your console, easily you can see how to address your array to get your desired result.
Now assuming that you want to extract the nested names in the object,
for two arrays inside each other, you should use two MAP which are nested.
this can give you the idea:
{ListOfData.map((item, index) => (
<div key={index}>
<h1>{item.title}</h1>
{item.content.map((c, i) => (
<div key={i}>
<h3>{c.title}</h3>
<h3>{c.description}</h3>
<hr />
</div>
))}
</div>
))}
Related
In trek_tours i have an array and inside array i have define object and inside object their are some array and the format is in below
treks_tours[
{
title: "Everest Base Camp",
Prices: [
"Price Start from 300 per/person",
"Note - if you are number of people then we can make you good discount!",
],
},{
title: "Jungle Safare & Knowing Villager Life Style",
Prices: [
"Price Start from 1650 per/person",
"Note - if you are number of people then we can make you good discount!",
],
}
]
In this section i want to see the title and price name of differrent objects but i got repeted title same time. anyone please help me!!!
const [tripPrice, setTripPrice] = useState({});
const price = () => {
treks_tours.map((price) =>
setTripPrice((prevState) => ({
...prevState,
price: price.Prices[0].split(" ")[3],
title: price.title,
}))
);
};
console.log(tripPrice);
useEffect(() => {
price();
}, []);
Output
So from that array of objects, you want to individually console.log() all of them?
If so you want to individually console.log() all the objects all you have to do is:
trek_tours.forEach((tour) => {
console.log(tour);
})
And then it will console.log() every object in array. Is that what you mean?
If all you want to do is setTripPrice to array trek_tours
then all to do is to say setTripPrice(trek_tours) - no need of anything else.
Then if you console.log(tripPrice) you get all the objects inside the array. If this is not what you mean please provide a codesandbox link
{treks_tours.slice(0, 3).map((trek_tour, key) => {
<p className="text-lg text-black">
Starting from : $ {trek_tour.Prices[0].split(" ")[3]}
</p>
);
})}
I am having trouble on posting the lists of data in my table, I hope you guys can help me with this issue, this is the error i am getting Error: Objects are not valid as a React child (found: object with keys {name}). If you meant to render a collection of children, use an array instead.
const columns = [
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
}
},
{
name: "dateregistered",
label: "Date Registered",
options: {
filter: true,
sort: false,
}
},
{
name: "department",
label: "Department",
options: {
filter: true,
sort: false,
}
},
];
const data = [
posts.map(post => [{name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}])
];
return (
<>
<MUIDataTable
title={"Deactivated Users"}
data={data}
columns={columns}
options={options}
/>
</>
)
I see two problems in your data constant. The first one, the .map method returns an array, so there is no need to wrap that value inside an array keys []. The other problem is that you are wrapping the .map return state object in array keys too, that is why the error of creating an object is displayed, because you are returning arrays inside the main mapped array [[{ name: ... }], [{ name: ... }]].
So basically the solution for your issue would be:
const data = posts.map(post => ({name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}))
Where the parenthesis allows the map method to directly return the object.
The issue is that data is being created as an array in an array in an array. This is why when you try const data = posts.map(post => ...) the error persists, as there is still an array in an array. After you try the above, also re-write
post => [{name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}]
to
post => ({name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'})
(Changing the square brackets to round)
P.S When you map over posts to build the data, you build a object with the the key "name" and the value "'post.firstname'". That value is a string literal and not accessing some other JS object (It will make "post.firstname" the value for all the post's. Same goes for the other keys.
I have an issue,
I have a select control component, which has options, inside options I'm adding array of options by mapping array staticPosts.
My code:
<SelectControl
label={__("Choose Static Block Page to show above header", "pirezmeta")}
onChange={ (value) => props.onChangeStaticContent(value) }
options={props.staticPosts && props.staticPosts.map(post =>
({value: post.id, label: post.title}))}
value={props.staticContent}
/>
Everything is fine, except I want to add empty option first, something like: {value: 0, label: "No value"}
How can I do it, can you help me, please?
A lot is going on in that prop. I'd declare the array above, separately - include the first {value: 0, label: "No value"} item, then add in the other mapped items:
const options = [
{value: 0, label: "No value"},
...props.staticPosts?.map(
post => ({value: post.id, label: post.title})
)
];
// ...
<SelectControl
label={__("Choose Static Block Page to show above header", "pirezmeta")}
onChange={ (value) => props.onChangeStaticContent(value) }
options={props.staticPosts && options}
value={props.staticContent}
/>
You could also put the combined array into state on mount or when the props change.
I am trying to dynamically render images from a local folder within my project
The object structure looks like this
{
id: 2,
text: 'How would you describe your level of influence in management of the farm?',
type: 'cardChoice',
choices: [
{
id: 1,
text: 'I am the primary decision maker',
questionId: 'Hm?',
value: 'I am the primary decision maker',
image: '1.jpg',
},
{
id: 2,
text: 'I hent',
questionId: 'Hrm?',
value: 'I',
image: '2.jpg',
},
{
id: 3,
text: 'I arm',
questionId: '?',
value: 'Irm',
image: '3.jpg',
},
],
},
In my component I select the folder that contains the images const baseUrl = '../../assets/images/CNA'
After that, in my return I try to render the images
<img src={`${baseUrl}'${questionChoice.image}'`} alt={questionChoice.text} />
The page renders, but my image isn't loading and it's showing my alt instead
Heres my full component
const CardChoiceQuestions = ({ cardChoiceArray, currentAnswer, updateCurrent, submitAnswer }) => {
const { id, value } = currentAnswer
const baseUrl = '../../assets/images/CNA'
return (
<ButtonContainer>
{cardChoiceArray.map(questionChoice => {
return (
<Button
active={questionChoice.id === id}
type="button"
key={questionChoice.id}
onClick={() => {
const answer = { id: questionChoice.id, value: questionChoice.value }
updateCurrent(answer)
submitAnswer()
}}
>
<p>{questionChoice.text}</p>
<img src={`${baseUrl}${questionChoice.image}`} alt={questionChoice.text} />
</Button>
)
})}
</ButtonContainer>
)
}
I don't have my laptop in front of me but a few things I noticed. Do you need a slash "/" after your base url? Also, the string concatenation should be completed in one set of brackets after the $ sign. Not sure if that's the issue try a few console.log(string path) amd verify it is going where you think it is. It looks like the path may be wrong. You may be better off conditional rendering images as opposed to building a dynamic url but either way it should render on change.
<img src={`${baseUrl}/${questionChoice.image}`} alt={questionChoice.text} />
use like this
Leaving this here in case someone comes across this...
<img src={require(`../../assets/images/CNA/${questionChoice.image}`)} alt={questionChoice.text} />
Not sure why I can't use ${baseUrl} but this works for now.
So, I'm assigned to work with vue at work, but VUE and I aren't friends yet. Currently I'm facing an issue that I don't know how to resolve - I'll explain it the best I can with the limited VUE knowledge I possess.
Simplistically I have a vue component, which looks like this:
Vue.component('input-checkboxes', {
template: '#input_checkboxes',
props: ['id', 'label', 'list', 'required', 'readonly']
});
Then I have a template that looks like this:
<template id="input_checkboxes">
<div>
<div>{{ label }}</div>
<div>
<label v-for="list_item in list">
<input type="checkbox" v-model="value" :name="id" :required="required" :readonly="readonly" value="{{ list_item.name }}"> {{ list_item.name }}
</label>
</div>
</div>
</template>
Then I have a rather large vue instance that I'll paste the relevant parts of here.
This variable is being created:
var some_form = {
form : {
Endless: '',
Amounts: '',
Of: '',
Names: '',
In: '',
The: '',
Form: '',
THIS-ONE: ''
}
};
var vm = new Vue({
el: '#form_product',
data: $.extend({
someStuff : 'some values',
someLists : {}
}, some_form),
ready: function() {
this.getLists(); // Fetches alot of lists
},
methods: {
this.$http.get(
framework.url('api','getLookupLists')
).then(function (response) {
this.lists = response.body;
this.pageLoading = false;
}.bind(this));
}
In the end I have my html page that amongst loads of other fields, that works very well, has this:
<input-checkboxes
id="THIS-ONE"
label="A Fitting Label"
:value.sync="form.SomeID"
:list="lists.AnAppropriateList">
</input-checkboxes>
So, that's the gist of the setup. I have numerous other components like input-text, that works just fine (someone else made it before I did), I even created other components by copying his way, and just changing some elements.
I cannot get checkboxes to work, I think my problem is that there are numerous inputs, and that I don't know how to bind the results of those inputs to my VUE instance.
I really hope this makes sense, because I would really like some pointers on how to get on... Maybe if someone duplicated this setup really simplistic and showed how the array of values from the checkboxes could be bound to the vue instance?
There are a couple of mistakes you are (or might be) making.
First of all, the value prop you pass down has to be an array (seems
like it's a string from your example)
value is not correctly set, you need to set it by doing :value="someValue"; you can't have curlies in an attribute.
Lastly, value should probably be the id of the item and not the name. You have a chance of a collision if you use the name.
Bonus: you don't need to use :name at all (unless you are submitting the form server side...? But I can't see why you would do that.)
Here's a simple working example to sum this up:
HTML
<label v-for="list_item in list">
<input type="checkbox" v-model="value" :required="required" :readonly="readonly" :value="list_item.id"> {{ list_item.name }}
</label>
JS
var app = new Vue({
el: 'main',
data: function () {
return {
value: [],
label: 'Label name',
readonly: false,
required: true,
list: [
{
name: 'Item 1',
id: 'item1'
},
{
name: 'Item 2',
id: 'item2'
}
]
}
}
})
I've also made a bin for you to try it out.