Certainly! Below is an example code snippet illustrating how you can achieve the described functionality with a parent and a child component in a Next.js app. This example uses React for the components and manages state with the useState
hook.
Let’s assume your parent component is named ParentComponent
and your child component is named ChildComponent
.
ChildComponent.js:
import React, { useState } from 'react';
const ChildComponent = ({ onDropdownChange }) => {
const [selectedValue, setSelectedValue] = useState('b2c');
const handleDropdownChange = (event) => {
const newValue = event.target.value;
setSelectedValue(newValue);
// Notify the parent about the selected value
onDropdownChange(newValue);
};
return (
<div>
<label>Select Provider:</label>
<select value={selectedValue} onChange={handleDropdownChange}>
<option value="b2c">B2C</option>
<option value="b2e">B2E</option>
</select>
</div>
);
};
export default ChildComponent;
ParentComponent.js:
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const [msalProvider, setMsalProvider] = useState('b2c');
const handleDropdownChange = (selectedValue) => {
// Update the msalProvider state in the parent component
setMsalProvider(selectedValue);
// You can perform other actions based on the selected value if needed
console.log('Selected Provider in Parent:', selectedValue);
};
return (
<div>
<h1>Parent Component</h1>
<ChildComponent onDropdownChange={handleDropdownChange} />
<p>Current MSAL Provider in Parent: {msalProvider}</p>
</div>
);
};
export default ParentComponent;
In this example, the ChildComponent
receives a callback function onDropdownChange
as a prop from its parent (ParentComponent
). When the dropdown value changes, it calls this callback, passing the selected value back to the parent. The parent updates its state (msalProvider
) accordingly. The parent also renders the current msalProvider
value, and you can see the updates when changing the dropdown in the child component.