Suppose the following:
import * as React from 'react';
const isMobile = true;
const App = () => {
const swipeStart = React.useCallback(() => {}, []);
const swipeMove = React.useCallback(() => {}, []);
const Component = isMobile
? <div onTouchStart={swipeStart} onTouchMove={swipeMove} />
: <React.Fragment />;
return (
<Component>
<span>child</span>
</Component>
);
}
How can I get this to work? I know that with styled-components or @emotion, there is an as prop, but I don’t want to install more libraries than necessary.
2
Answers
It’s easies to assign
Component
to just the type of element.Then pass the props to the
Component
.Since
React.Fragment
won’t do anything with those props it gets the desired behaviour.(an if / else with return would also work)
Should you don’t want to pass the props if it’s not needed.
Another option is to make an empty object, and only add the props if
isMobile
. Then spread (...
) the object toComponent
Make your
Component
into a component, currently its something called Component that contains some JSX.eg.
const X = <div/>
<- JSXconst X = (p) => <div/>
<- Componenteg.
Note:
{...p}
is just a way of passing all the props, the main one in your case ischildren
.Also seen as you mentioned Typescript, to keep Typescript happy you could just do ->
const Component = (p: {children:React.ReactNode} ) => isMobile
Also one issue with this, even if you have
isMobile
set to false, it’s going to create 2 useCallback’s that never get used. To get around this you could split this up.eg.
In above if you set
isMobile
to false,useCallback
is then never even used.