Please tell me is it possible to pass props from a child Astro
component to the parent? Something like callback in React
:
<Component callBack={arg=>{
//do something with arg
}} />
Are there some analogues in Astro
? Thanks for attention!
Please tell me is it possible to pass props from a child Astro
component to the parent? Something like callback in React
:
<Component callBack={arg=>{
//do something with arg
}} />
Are there some analogues in Astro
? Thanks for attention!
Props can only flow downward in Astro, the closest you can get to doing something like what your describing is passing arguments to slot functions
Example from the docs:
// src/components/Shout.astro
---
const message = Astro.props.message.toUpperCase();
---
{ Astro.slots.has('default') &&
<Fragment set:html={Astro.slots.render('default', [message])} />
}
// src/pages/index.astro
---
import Shout from "../components/Shout.astro";
---
<Shout message="slots!">
{(message) => <div>{message}</div>}
</Shout>
renders into
<div>SLOTS!</div>
you can't pass props from child
component to parent
component. if you want to expose some methods of child
component to parent
you can use useImperativeHandle
hook.
function Form() {
const ref = useRef(null);
function handleClick() {
ref.current.focus(); // focus is method from `child
}
return (
<form>
<MyInput label="Enter your name:" ref={ref} />
<button type="button" onClick={handleClick}>
Edit
</button>
</form>
);
}
const MyInput = forwardRef(function MyInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => {
return {
focus() {
inputRef.current.focus();
},
scrollIntoView() {
inputRef.current.scrollIntoView();
},
};
}, []);
return <input {...props} ref={inputRef} />;
});