Sometimes, we want to transfer all props except one to a React component.
In this article, we’ll look at how to transfer all props except one to a React component.
Transfer All Props Except One to a React Component
To transfer all props except one to a React component, we can destructure the properties we want to pass into the child component with the rest syntax.
For instance, we write:
import React from "react";
const Foo = (props) => {
return <div>{JSON.stringify(props)}</div>;
};
export default function App() {
const props = { foo: 1, bar: 2, baz: 3 };
const { foo, ...restProps } = props;
return <Foo {...restProps} />;
}
We have a Foo
component that renders the props
object.
In App
, we have the props
object with some properties we want to pass to Foo
as props.
We want to pass everything except the foo
property.
To do this, we destructure props
and put all properties except foo
into the restProps
object.
Then we pass the properties in restProps
into Foo
with the destructuring syntax.
Therefore, we should see {"bar":2,"baz":3}
rendered.
Conclusion
To transfer all props except one to a React component, we can destructure the properties we want to pass into the child component with the rest syntax.