i want to return jsx if some condition is true if not undefined should be returned.
below is my code,
const showInfo = (item) { return ( <div> <div> <span>name</span> </div> <div> <button>click</button> </div> </div> ); } const Parent = () => { return ( <Child onDone = {({item}) => { notify ({ actions: (condition === 'value1' || condition === 'value2' ) && showInfo(item) //should put this condition into showInfo method }) }} /> ); }
what i am trying to do? the above code works. but now i want to put the condition inside the showInfo method. so if condition is true return jsx and if condition is false should return undefined.
what i have tried? I have tried something like below
const showInfo = (item) { return {(condition === 'value1' || condition === 'value2' ) ? <div> <div> <span>name</span> </div> <div> <button>click</button> </div> </div> : undefined } ); } const Parent = () => { return ( <Child onDone = {({item}) => { notify ({ actions: showInfo(item) //error here }) }} /> ); }
but the above tried code, gives error “Type ‘void’ is not assignable to type ‘ReactNode'” at actions statement.
could someone help me with this. i am not sure if i have used ternary operator properly. thanks.
EDIT
after trying one of the answers provided,
notify is a method that is returned from usehook and it evaluates to the component below
const Something: React.FC<SomethingProps> = ({ description, actions, ...props }) => ( <Header> <Title>{title}</Title> </Header> {(description ||actions) && ( <Body> //this is displayed {description && <Description>{description}</Description>} {actions && <Actions>{actions}</Actions>} </Body> )} );
here the component is displayed when the condition fails in showInfo component.
in showInfo i am returning undefined if condition fails but still in the Something component the is displayed even though i have {description || actions}
i am not sure what is happening here.what is the condition i have to check for actions to not display in this case
i have tried
{(description ||actions !== 'false') && ( <Body> //this is displayed {description && <Description>{description}</Description>} {actions && <Actions>{actions}</Actions>} </Body> )}
and this works. i am wondering why i should specifically mention
actions !== 'false'
instead of actions only could someone help me with this. thanks.
Answer
If you want to return jsx from function you should wrap them inside some component. In this case you cen use <React.Fragment> or just <>. Another problem which I can see is that you probably forgot about arrow in you arrow function. Also don’t know from where variable names condition
comes from.
const showInfo = (item) => { return ( <> { condition === "value1" || condition === "value2" ? ( <div> <div> <span>name</span> </div> <div> <button>click</button> </div> </div> ) : undefined} </> ); };