I am new to React and trying to pass data (director, nonDirector) from my child functional component to a parent class component.
My code is below, what do I need to do to make it work?
Class parent component
export default class ProfileEditor extends React.Component<IProfileEditorProps, IProfileEditorState> {
constructor(props: IProfileEditorProps) {
super(props);
this.state = {
data: null,
}
this.updateProfile = this.updateProfile.bind(this);
}
public updateProfile(director, nonDirector) {
console.log('hello', director, nonDirector);
}
<MultiSelect
options={ profile?.Declarations.length == 0 ? countries : this.combineProfileAndCountrys() }
updateProfile={updateProfile()}
/>
Child functional component
export const MultiSelect = ({ options, updateProfile }) => {
const [nonDirector, setNonDirector] = React.useState();
const [director, setDirector] = React.useState();
<PrimaryButton text='Save' onClick={ updateProfile(nonDirector, director) } />
</Fragment>
);
In your parent component you shouldn't be calling the function in the onClick handler. You want to pass the reference to the function to it instead.
updateProfile={updateProfile}
A similar issue is occurring in your child component. You don't want to call the function and have the results of it returned to the handler, you want to assign a function to the handler that can then call the updateProfile function when its triggered.
onClick={() => updateProfile(nonDirector, director)}