I am currently building a "Quote Builder" in React and using the WPAPI to hook into the data within WordPress. This uses ACF to gather further data - which I have done (screenshot attached).
I then have an onChange
function which grabs the data (from the screenshot), which will then need to update the state:
const quoteTypeChange = async (e) => {
e.preventDefault();
const optionValue = e.target.value;
try {
await wp.quoteType().id(optionValue).then((data) => {
const quoteTypeDetails = data;
// useState update here //
}).catch((error) => {
// Error //
});
} catch (error) {
// Error //
}
}
Within the "Quote Builder" it will display the data into a table - which I have build the front-end of it and its using the following components:
<QuotePhaseTitle title="Title goes here" style="primary" />
and:
<QuoteComponentRow inclusion="Inclusion goes here" deDesktop="2" deMobile="2" deWireframe="2" digital="2" notes="Test notes" />
What I want to be able to do is using the data from the screenshot, map out the data and structure it using those components. From the data the "phase" element will use "QuotePhaseTitle" component and the "quote" will use the "QuoteComponentRow" component, but those can exist in any order and repeated however often that is needed - but they have to go in the order that appears in the data flow.
How would you go about doing this?
It sounds like the key bits of information you need are that
<QuotePhaseTitle title="Title goes here" style="primary" />
can be thought of as compiling to something like {elementType: 'QuotePhaseTitle', props: { title: "Title goes here", ... }}
. (It's not exactly that, but you can think of it like that.) So if you want a list of elements in your component based on data, you can use standard JavaScript techniques to create that array of React elements and React will render it.
For your data structure, you probably need two nested loops like this:
const quoteList = []
data.acf.phase.forEach(phase => {
quoteList.push(<QuotePhaseTitle title={phase.phase} style="primary" />)
phase.quote.forEach(quote => {
quoteList.push(<QuoteComponentRow inclusion={quote.inclusion} ... />)
})
})
You can create this array first and assign it to state or assign your data to state and then have this code run before returning the JSX.
To render your quotelist
, you can just include the array of elements as a child in the JSX.
return (
<div>
{quoteList}
</div>
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.