Having a component that accepts some props:
<MyComponent first="first" second="second" third="third" />
We can create an object:
const mockData = {
first: 'test1',
second: 'test2',
third: 'test3'
};
and use it as props in the following way: <MyComponent {...mockData} />
and it works fine.
What I want is to use just first two elements from the mockData
object as none of them are required/mandatory it should not be a problem.
So I've tried like this: <MyComponent {...mockData.first, ...mockData.second} />
but it doesn't work.
Of course it can be written like <MyComponent first={mockData.first} second={mockData.second} />
but this is just an example with few elements as my real problem has more elements.
Is there a way to do that?
CodePudding user response:
You have to create a type derived of mock data like:
type MyComponentType = Pick<mockdata, "first">
CodePudding user response:
You can use the object spread syntax:
const {third, ...rest} = mockData;
// now the variable rest has all the properties from mockData except third
<MyComponent {...rest}/>
Since you said you have many more properties, you can extract as many properties you want by simply including them before the destructuring, eg:
const {third, fourth, fifth, /* etc */ ...rest} = mockData;
CodePudding user response:
const mockData = {
first: 'test1',
second: 'test2',
third: 'test3'
};
<MyComponent props={ mockData } />
const MyComponent = ({first, second, third}) => {
return (
<div>
first = {first}
second = {second}
third = {third}
</div>
)};
this should work for you