Conditionally activate Material UI tooltip? - javascript

I have the following React component using Material UI:
const MyButton = ({ warningText }) => (
<Tooltip title={warningText}>
<Button>Do action</Button>
</Tooltip>
)
Currently, this shows an empty tooltip when warningText is undefined. Instead I would like to show no tooltip at all. Is there a way to conditionally surpress the tooltip in these cases?
Off course I could just use an if statement to not render the tooltip component, but this would lead to rather ugly code in my opinion.

Should be
<Tooltip title={warningText == null ? "" : warningText}>
<Button>Do action</Button>
</Tooltip>
the docs say that it won't be displayed if the string length is zero.
https://material-ui.com/api/tooltip/
Tooltip title. Zero-length titles string are never displayed.

If you're looking to manually play around for customization, you can try to use the following solution:
As per the documentation, you can use the open prop and mouse events to handle it manually.
In the following scenario, we will use state to set showing the tooltip when we enter the mouse over the element, and we will also use text && to assert that text has a value, this will prevent the tooltip from showing when text is undefined.
const [showTooltip, setShowTooltip] = useState(false);
<Tooltip
open={text && showTooltip}
onMouseEnter={() => { setShowTooltip(true) }}
onMouseLeave={() => { setShowTooltip(false) }}
placement="top" title={text}
>
<div>
{text}
</div>
</Tooltip>
Note, the mui-tooltip is not a perfect component to begin with and is not very straight forward, this solution works for me but might not work in your situation as is, I will try to put it out, you can try to make it work on your end.
If it doesn't work for you, please leave a comment and I'll try to help.

You should take a look at https://material-ui.com/api/tooltip/
There are options like
disableFocusListener
disableHoverListener
disableTouchListener
interactive
I think interactive={true} should fit your needs best
<Tooltip title={warningText} interactive={!warningText}>...</Tooltip>

Related

Conditionally render border colour React Native

I'm trying to conditionally change my border color based on whether the textInput is under focus or not.
<View
style={focus? { ...styles.inputRow, ...bgColorOnFocus }: { ...styles.inputRow, ...bgColorOnBlur }}>
This works as expected, but I'm having to repeat inputRow styles twice. I've been trying to improve the code with the following code where I add the object based on whether it's on focus or not and it's throwing an error.
<View style ={
{...styles.inputRow, focus? ...bgColorOnFocus: ...bgColorOnBlur}}
>
I'm not sure if I'm being silly, or if there's something missing that I'm not familiar with? Thanks for looking into this!
Typically a style prop accept an array as a value:
<View style={[styles.inputRow, isFocus ? bgColorOnFocus : bgColorOnBlur]}>
is a valid way to conditionally render some style.

How to get a ref for an instance of React Select's AsyncCreatable to focus the Select inside it?

I have seen that Select has a ref prop that works as it is usual in the React world.
But I have a piece of code that uses it indirectly, through AsyncCreatable:
<AsyncCreatable>
{({ default: AsyncCreatableSelect }) => (
<AsyncCreatableSelect
ref={this.focusRef}
className="react-select-container"
classNamePrefix="react-select"
defaultOptions={this.props.choices || []}
styles={customSelectStyles}
theme={selectTheme}
components={{ DropdownIndicator, Option }}
isMulti
value={selectedOption || []}
loadOptions={this.loadOptions}
onChange={this.handleChange}
placeholder={this.props.intl.formatMessage(messages.select)}
noOptionsMessage={() =>
this.props.intl.formatMessage(messages.no_options)
}
/>
)}
</AsyncCreatable>
The problem with the above code is that the following line in it does not work:
ref={this.focusRef}
The reason I want to use a ref here is that I want to focus the Select.
How can I do this? I searched the docs of react-select and superficially searched the source code. I think I saw that the Select has a focus method but I do not know how to use it.
I rapidly read this but with no use because in that case the Select is used directly (not through HOCs such as AsyncCreatable).
Thank you.
Update
I also tried putting the ref on the AyncCreatable JSX tag instead of on the AsyncCreatableSelect, with no use.

How to add style - like margin - to react component?

So, expect two simple components that I have built:
import {Input} from 'semantic-ui-react';
import {Select} from 'semantic-ui-react';
const CategoriesDropdown = ({categories, onCategorySelected, selectedCategory}) => {
const handleChange = (e, {value})=>{
onCategorySelected(value);
};
return (
<Select placeholder="Select category" search options={categories} onChange={handleChange} value={selectedCategory} />
);
};
const IdentifiersInput = ({identifiers, onIdentifiersChanged}) => {
return (
<Input placeholder="Enter identifiers..." value={identifiers} onChange={onIdentifiersChanged}/>
);
};
Nothing fancy so far.
But now, I am building another component that displays those two in a flexbox row:
<Box>
<CategoriesDropdown categories={categories} selectedCategory={selectedCategoryId}
onCategorySelected={this.selectCategory}/>
<IdentifiersInput identifiers={identifiers} onIdentifiersChanged={this.changeIdentifiers}/>
</Box>
Unfortunately they are both displayed right next to each other without any margin in between.
Usually, I would just add a margin-left style to the second element, but because it is a React component, that doesn't work. Using style={{marginLeft: '20px'}} doesn't work as well, because the IdentifiersInput component doesn't use it.
I know that I can fix it by doing this: <Input style={style} ... inside the IdentifiersInput component.
However, this seems to be a very tedious way of achieving this goal. Basically, I have to add this to every single component I am writing.
I clearly must be missing something here. How am I supposed to apply such layout CSS properties to React components?
I think I understand.
1) Applying CSS directly to React Components does not work--I can confirm that.
2) Passing props down to the low level elements is tedious, confirmed but viable.
Notice hasMargin prop:
<Box>
<CategoriesDropdown
categories={categories}
selectedCategory={selectedCategoryId}
onCategorySelected={this.selectCategory}
/>
<IdentifiersInput
identifiers={identifiers}
onIdentifiersChanged={this.changeIdentifiers}
hasMargin
/>
</Box>
Possible input:
const IdentifiersInput = ({identifiers, onIdentifiersChanged, className, hasMargin }) => {
return (
<Input
className={className}
placeholder="Enter identifiers..."
value={identifiers}
onChange={onIdentifiersChanged}
style={hasMargin ? ({ marginLeft: '0.8rem' }) : ({})}
/>
);
};
NOTE: I do not like style as much as I like adding an additional class because classes can be adjusted via media queries:
const IdentifiersInput = ({identifiers, onIdentifiersChanged, className, hasMargin }) => {
const inputPosition = hasMargin ? `${className} margin-sm` : className
return (
<Input
className={inputPosition}
placeholder="Enter identifiers..."
value={identifiers}
onChange={onIdentifiersChanged}
/>
);
};
If you find inputPosition too verbose as shown above:
className={hasMargin ? `${className} margin-sm` : className}
3) You could accomplish it using a divider Component, sacreligious yet rapidly effective
<Box>
<CategoriesDropdown
categories={categories}
selectedCategory={selectedCategoryId}
onCategorySelected={this.selectCategory}
/>
<div className="divider" />
<IdentifiersInput
identifiers={identifiers}
onIdentifiersChanged={this.changeIdentifiers}
/>
</Box>
You can use media queries and control padding at any breakpoints if desired.
4) CSS pseudo-elements or pseudo-classes, I don't see any mention of them in answers so far.
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
CSS Tricks: https://css-tricks.com/pseudo-class-selectors/
Usually, when you have a random collection of DOM elements, you can calculate a way using CSS to wrangle them into the correct position. The list of available pseudo-classes is in that MDN link. It honestly helps to just look at them and reason about potential combinations.
My current issue is I don't know what is in <Box /> other than it probably has a div with display: flex; on it. If all we have to go on is that and the div is called <div className="Box">, maybe some CSS like this will fix it:
.Box {
display: flex;
}
.Box:first-child {
margin-right: 0.8rem;
}
This is why it is extremely important to know exactly what the surrounding elements will or can be, and exactly which CSS classes/IDs are nearby. We are basically trying to hook into something and correctly identify the left child in Box and add margin to the right of it, or target the right child and add margin to the left of it (or depending on everything, target both and split the additional margin onto both).
Remember there is also ::before and ::after. You are welcome to get creative and find a solution that involves position:relative and position: absolute and adds no markup.
I will leave my answer like that for now, because I think either you already thought about pseudo-selectors, or you will quickly find something that works :)
That or the divider is actually quite viable. The fact you can use media queries alleviates you from concern of future management or scalability of the components. I would not say the same about <div style={{}} />.
As your component specializes another single component it would be a good practice to pass any props your wrapper does not care for to the wrapped component. Otherwise you will loose the ability to use the api of the original <Input>component including passing styles to it:
const IdentifiersInput = ({identifiers, onIdentifiersChanged, ...props}) = (
<Input
{...props}
placeholder="Enter identifiers..."
value={identifiers}
onChange={onIdentifiersChanged}
/>
);
There may be valid cases where you explicitly want to prevent users to be able to pass props to the wrapped component but that does not look like one of those to me.
I clearly must be missing something here. How am I supposed to apply
such layout CSS properties to React components?
You did not miss something. A react component has no generic way to be styled because it is no DOM element. It can have a very complicated and nested DOM representation or no representation at all. So at some point you as the designer of the component have to decided where the styles, ids and class names should be applied. In your case it is as easy as passing these props down and let the <Input> and <Select>component decide. I find that to be quite elegant rather than tedious.
I see several ways to do it, but the easiest I see would be to pass a className to IdentifiersInput like so:
<IdentifiersInput className="marginLeft" identifiers={identifiers} onIdentifiersChanged={this.changeIdentifiers}/>
Inside IdentifiersInput I would just set that class to the Input:
const IdentifiersInput = ({identifiers, onIdentifiersChanged, className}) => {
return (
<Input className={className} placeholder="Enter identifiers..." value={identifiers} onChange={onIdentifiersChanged}/>
);
};
Semantic UI's Input element can receive a className prop.
I would then just use CSS or SCSS to add styles to that particular class. In this case, the margin you want.

React Native: onContentSizeChange event on TextInput element does not work on Android

I have a problem with TextInput event 'onContentSizeChange' on Android device.
Actually it is not been fired when I type message until the end of line and text goes to the next line the height of TextInput is not updated.
example:
return (
<TextInput
{...this.props}
multiline={Boolean(true)}
onChangeText={(text) => {
this.setState({text})
}}
onContentSizeChange={(event) => {
this.setState({height: event.nativeEvent.contentSize.height})
}}
style={[ additionalStyles, {height: this.state.height}, {fontSize: config.defaultFontSize} ]}
value={this.state.text}
underlineColorAndroid={'rgba(0,0,0,0)'}
/>
)
Does anybody know why it may happens?
P.S. Helped using onChange instead of onContentSizeChange
Please see React Native issue #11692. This looks like it will be fixed in an upcoming release. It's not clear, and it was only fixed a couple of weeks ago but maybe it will be in 0.46.
try onContentSizeChange
onContentSizeChange={e=>{
let inputH = Math.max(e.nativeEvent.contentSize.height, 35)
if(inputH>120) inputH =100
setIputHeight(inputH)
}}
onContentSizeChange does not return the size of the content, but on the container. It's still not fixed, which is also documented in an issue on the official react-native github repo

Show/Hide ReactJS components without losing their internal state?

I've been hiding/showing react components by not rendering them, for example:
render: function() {
var partial;
if (this.state.currentPage === 'home') {
partial = <Home />;
} else if (this.state.currentPage === 'bio') {
partial = <Bio />;
} else {
partial = <h1>Not found</h1>
}
return (
<div>
<div>I am a menu that stays here</div>
Home Bio
{partial}
</div>
);
}
but just say that the <Bio/> component has lots of internal state. Everytime I recreate the component, it loses it's internal state, and resets to it's original state.
I know of course that I could store the data for it somewhere, and pass it in via props or just globally access it, but this data doesn't really need to live outside of the component. I could also hide/show components using CSS (display:none), but I'd prefer to hide/show them as above.
What's the best practice here?
EDIT: Maybe a better way to state the problem is to use an example:
Ignore React, and assume you were just using a desktop app that had a configuration dialog with a Tab component called A, which has 2 tabs, named 1 and 2.
Say that tab A.1 has an email text field and you fill in your email address. Then you click on Tab A.2 for a second, then click back to Tab A.1. What's happened? Your email address wouldn't be there anymore, it would've been reset to nothing because the internal state wasn't stored anywhere.
Internalizing the state works as suggested in one of the answers below, but only for the component and it's immediate children. If you had components arbitrarily nested in other components, say Tabs in Tabs in Tabs, the only way for them to keep their internal state around is to either externalize it somewhere, or use the display:none approach which actually keeps all the child components around at all times.
It just seems to me that this type of data isn't data you want dirtying up your app state... or even want to even have to think about. It seems like data you should be able to control at a parent component level, and choose to either keep or discard, without using the display:none approach and without concerning yourself with details on how it's stored.
One option would be to move the conditional inside the component itself:
Bio = React.createClass({
render: function() {
if(this.props.show) {
return <p>bio comp</p>
} else {
return null;
}
}
});
<Bio show={isBioPage} />
Whether this is "best practise" or not probably depends on the exact situation.
Unfortunately, style={{display: 'none'}} trick only works on normal DOM element, not React component. I have to wrap component inside a div. So I don't have to cascade the state to subcomponent.
<div className="content">
<div className={this.state.curTab == 'securities' ? 'active' : ''}>
<Securities />
</div>
<div className={this.state.curTab == 'plugins' ? 'active' : ''}>
<Plugins />
</div>
</div>
Looks like official documentation suggests hiding stateful children with style={{display: 'none'}}
The fundamental problem here is that in React you're only allowed to mount component to its parent, which is not always the desired behavior. But how to address this issue?
I propose the solution, addressed to fix this issue. More detailed problem definition, src and examples can be found here: https://github.com/fckt/react-layer-stack#rationale
Rationale
react/react-dom comes comes with 2 basic assumptions/ideas:
every UI is hierarchical naturally. This why we have the idea of components which wrap each other
react-dom mounts (physically) child component to its parent DOM node by default
The problem is that sometimes the second property isn't what you want
in your case. Sometimes you want to mount your component into
different physical DOM node and hold logical connection between
parent and child at the same time.
Canonical example is Tooltip-like component: at some point of
development process you could find that you need to add some
description for your UI element: it'll render in fixed layer and
should know its coordinates (which are that UI element coord or
mouse coords) and at the same time it needs information whether it
needs to be shown right now or not, its content and some context from
parent components. This example shows that sometimes logical hierarchy
isn't match with the physical DOM hierarchy.
Take a look at https://github.com/fckt/react-layer-stack/blob/master/README.md#real-world-usage-example to see the concrete example which is answer to your question (take a look at the "use" property):
import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
return (
<Cell {...props}>
// the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
<Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
hideMe, // alias for `hide(modalId)`
index } // useful to know to set zIndex, for example
, e) => // access to the arguments (click event data in this example)
<Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
<ConfirmationDialog
title={ 'Delete' }
message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
confirmButton={ <Button type="primary">DELETE</Button> }
onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
close={ hideMe } />
</Modal> }
</Layer>
// this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
<LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
<div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
<Icon type="trash" />
</div> }
</LayerContext>
</Cell>)
// ...

Categories

Resources