I currently have a local React website (first project, so learning as I go) which has a select field that is pulling the options in from a database. That bit is fine. When I create a click function "onChange" to then get data from the database, this works fine.
My issue is that I want to be able to grab the data from the JSON data and append the data into a component. I currently have the following component set up, which works when I add this onto the page manually:
<QuotePhaseTitle title="Test Title" style="primary" />
So what I basically want to do is within the "onChange" function, get the data (which I can do easily enough) and then pass that to the "title" and "style" props. Once that has been passed, I then need to be able to return that data and input into the page somewhere.
Below is an example of the function so far (I am using WPAPI):
const quoteTypeChange = async (e) => {
e.preventDefault();
const optionValue = e.target.value;
try {
await wp.quoteType().id(optionValue).then((data) => {
const quoteTypeDetails = data;
// Ideall want to pass in the <QuotePhaseTitle title="Test Title" style="primary" /> component, add in the data and then display that on the page //
}).catch((error) => {
// Error //
});
} catch (error) {
// Error //
}
}
How would I go about doing this? Sorry if this is a basic question.
CodePudding user response:
The code itself doesn't "pass values to components", it doesn't really interact with components at all in general. The code updates state. The components use state. So your component might define two state values, for example:
const [title, setTitle] = useState('Test Title');
const [style, setStyle] = useState('primary');
And you would use that state in the JSX:
<QuotePhaseTitle title={title} style={style} />
Then all you need to do is update the state values:
wp.quoteType().id(optionValue).then((data) => {
setTitle(data.someValue);
setStyle(data.someOtherValue);
})
Structurally this is fundamental to React. State drives display, logic updates state.
CodePudding user response:
You need to create a state, so when the data comes from server, you put them on the state for example this.setState({ title: data.title })
o using hooks const [title, setTitle] = useState(); setState(data.title);
And then pass the title value to your component: <QuotePhaseTitle title={this.state.title} style="primary" />
of <QuotePhaseTitle title={title} style="primary" />
if you are using hooks.
Also you can instantiate the hook value or the state with a default value.