'Ignore other react props if one prop is true
Im trying to make it so that if on prop is true, all others will be ignored. My current react code looks like this:
<Component isTrue={true}/>
<Component foo='bar' someProp={true}/>;
But this causes problems because in my Component.tsx file because the Props interface
interface Props {
isTrue?: boolean;
foo?: string;
someProp?: boolean;
}
Typescript warns me about the props maybe being undefined which i can fix by adding more lines of code but its pretty troublesome to do everytime i make a new prop.
So i want to know if its possible to have separate props or something to fix this problem, thanks in advance :)
Solution 1:[1]
Maybe an alternative way is to separate the concerns of component prop types into several (private) components. For example, for
interface Props {
isTrue?: boolean;
foo?: string;
someProp?: boolean;
}
- For the
Component, can give all props directly to<Component isTrue={true/false} foo='bar' someProp={true}/>;as optional props - Inside
Component, check for theisTrue.if (isTrue), return a component<TrueComponent/>where you can ignore all other props inside the logic ofTrueComponent - Otherwise, return another component
<FalseComponent/>, where you can ignore thisisTrueprops, but requires all other props to be required. There would be one layer of nonnull props check that cannot be avoided inComponent, but I think that would be the minimal effort and would be type-safe.
Solution 2:[2]
So, you could do it like this if you didn't want two different components.
export type IMyComponentPropsTruth = {
isTrue: boolean;
};
export type IMyComponentPropsFalse = {
foo: string;
someProps: string;
};
export const MyComponent = (
props: IMyComponentPropsTruth | IMyComponentPropsFalse
) => {
const mytruthyProps = props as IMyComponentPropsTruth;
const myfalseProps = props as IMyComponentPropsFalse;
if (mytruthyProps && mytruthyProps.isTrue) {
return <div>THE TRUTH IS OUT THERE</div>;
} else {
return (
<div>
keep looking {myfalseProps.foo} {myfalseProps.someProps}
</div>
);
}
};
import "./styles.css";
import { MyComponent } from "./MyComponent";
export default function App() {
return (
<>
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
<MyComponent isTrue={true} />
<MyComponent foo="looked" someProps="404" />
</>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark |
| Solution 2 | Nikki9696 |
