I am working on a react component and I need to limit the displayed text in a field that changes based on a input component. I am trying to make it so when the text box input becomes longer than the width of the component, to display what can fit followed by ... . I have something that works but it uses width: field to set how wide the text can go and I am looking for a responsive way to make it fit more or less text
<span
className='itemTitle'
onMouseLeave={this.handleMouseLeave}
id = 'itemTitle'
style = {{width: '420px', "whiteSpace": "nowrap",
overflow:"hidden !important",
'textOverflow': "ellipsis",
'display': 'inline-block'}}>
{prompt || card.get('promptText')}
</span>
The solution I came up with is as follows.
From the parent component which renders a Title Component, I add a ref and on add a resize eventlistener which sends new props to the ItemTitle component.
<div ref={input => {{this.rangeInput = input}}}>
<ItemTitle
prompt={prompt}
{...this.props}
width = {this.state.width}
/>
</div>
updateDimensions = () => {
this.setState({
width: this.rangeInput.offsetWidth
})
}
componentDidMount() {
this.updateDimensions();
window.addEventListener("resize", this.updateDimensions);
}
/**
* Remove event listener
*/
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
Then in ItemTitle.js
<span
className='itemTitle'
onMouseLeave={this.handleMouseLeave}
id = 'itemTitle'
style = {{width: this.state.width - 140, "whiteSpace": "nowrap",
overflow:"hidden !important",
'textOverflow': "ellipsis",
'display': 'inline-block'}}>
{prompt || card.get('promptText')}
</span>
Related
I have a page that has table component. Inside this table component are a DataGrid, and 2 button components, all using Material UI. I also have a navbar component that uses the MUI AppBar component with a button group. I originally developed this app on my extra large monitor and everything looked find, but as soon as I moved it to a regular monitor, I noticed that the navbar and DataGrid table were not scaling properly and that my buttons disappear underneath the footer.
If I 'scrunch' or reduce the browser window, a scrollbar appears, but its outside the table. I am not making this app for mobile so I just need it to display properly in common computer screen sizes. I want to focus on the table and buttons first. I have tried to put the button's outside the Table component, but I get the same result, so I am going to leave them inside the table component for now. I have already tried to wrap the table component in a div using display: 'flex' but it doesn't seem to change anything. Any suggestions on what I can do to get this to display properly? Is there a way to wrap everything in the App.js to get responsive action for all components?
import React, { useState, useEffect } from 'react';
import { DataGrid, GridToolbar} from '#mui/x-data-grid';
import EditJobModal from './EditJobModal';
import ClearButton from './ClearButton';
const MyTable = ({columns, data, clearStatus}) => {
const [selectionModel, setSelectionModel] = useState([]);
const [selectedRows, setSelectedRows] = useState([{'id': ''}]);
const buttonToTable = (clearStatus) => {
if (clearStatus === true) {
setSelectionModel([]);
setSelectedRows([{'id': ''}]);
}
}
return (
<div style={{ height: 450, width: '100%' }}>
<div style={{ display: 'flex', height: '100%' }}>
<div style={{ flexGrow: 1 }}>
<DataGrid
sx={{
boxShadow: 2,
border: 1,
margin: '5px'
}}
columns={columns}
rows={data}
pageSize={5}
rowsPerPageOptions={[10]}
checkboxSelection={false}
components={{ Toolbar: GridToolbar }}
selectionModel={selectionModel}
onSelectionModelChange={(ids) => {
if (ids.length > 1) {
let selectionSet = new Set(selectionModel);
let result = ids.filter((s) => !selectionSet.has(s));
setSelectionModel(result);
} else {
let selectedIDs = new Set(ids);
console.log(selectedIDs);
let selectedRow = data.filter((row) =>
selectedIDs.has(row.id),
);
setSelectedRows(selectedRow);
setSelectionModel(ids[0]);
}
}}
/>
<EditJobModal jobData={selectedRows}/>
<ClearButton buttonToTable={buttonToTable}/>
</div>
</div>
</div>
);
};
export default MyTable;
I'm trying to create a "collapsible text" react component that allows a user-determined number of lines to be displayed. I'm using the line-clamp CSS property to do this, for the most part. On the JavaScript side of things, I want to selectively render a button that toggles the effect based on whether the content to be shown is greater in height than the number of lines to be shown multiplied by their line height. This is working fairly well in Firefox and Chrome. I can get the line height of the element after it's rendered, and I can multiply that by the number of lines that the user wants shown to approximate the height of the content. I can use that to set a min-height CSS property, and I can compare that value against the scroll height of the content. The problem is, I'm getting the same value for the scroll height of the content in Firefox and Chrome, but NOT in Safari.
const CollapsibleText = ({
text,
linesToShow,
markdown = false,
containerStyles,
textStyles,
buttonStyles,
handleScroll,
}) => {
const [isActive, setIsActive] = useState(false)
const contentRef = useRef(null)
const [displayButton, setDisplayButton] = useState(false)
const [contentMinimumHeight, setContentMinimumHeight] = useState(null)
const windowSize = useWindowSize()
const linesShown = windowSize.mobile
? parseInt(linesToShow[0])
: parseInt(linesToShow[1])
const handleToggleIsActive = () => {
if (isActive && handleScroll) {
handleScroll()
}
setIsActive(!isActive)
}
useEffect(() => {
const contentLineHeight = parseInt(
window
.getComputedStyle(contentRef.current, null)
.getPropertyValue('line-height')
)
const contentHeight = contentRef.current.scrollHeight
// Adding 5 here to offset rounding that seems to occur in actual pixel values of rendered output, value of 5 is arbitrary.
const linesToShowHeight = contentLineHeight * linesShown + 5
setContentMinimumHeight(linesToShowHeight)
console.log('Content height: ', contentHeight)
console.log('Lines to show height: ', linesToShowHeight)
if (contentHeight > linesToShowHeight) {
setDisplayButton(true)
}
if (contentHeight < linesToShowHeight) {
setDisplayButton(false)
}
}, [windowSize])
return (
<div sx={{ ...containerStyles }}>
<div
sx={{
display: '-webkit-box',
'-webkit-line-clamp': !isActive ? linesToShow : 'none',
lineClamp: !isActive ? linesToShow : 'none',
'-webkit-box-orient': 'vertical',
overflow: 'hidden',
outline: '2px solid red',
textOverflow: 'ellipsis',
minHeight: contentMinimumHeight,
'&:first-child': {
marginTop: '0px',
},
}}
>
{markdown ? (
<div
ref={contentRef}
sx={{
...textStyles,
'& *:first-child': {
marginTop: '0px',
// marginBottom: '0px',
},
}}
dangerouslySetInnerHTML={{
__html: text,
}}
/>
) : (
<p
ref={contentRef}
sx={{
whiteSpace: 'pre-wrap',
...textStyles,
}}
>
{text}{' '}
</p>
)}
</div>
{displayButton && (
<Button
variant="viewMore"
sx={{ marginTop: '20px', ...buttonStyles }}
onClick={handleToggleIsActive}
>
{!isActive ? 'Read more' : 'Read Less'}{' '}
<ChevronDown
styles={{ transform: !isActive ? 'none' : 'rotate(180deg)' }}
/>
</Button>
)}
</div>
)
}
export default CollapsibleText
To determine the content height, I'm using a ref and grabbing the scroll height of the element in question. I get the same value in Chrome and Firefox, but a larger value in Safari, which breaks my ability to selectively render the "toggle" button I'm trying to implement.
I'm comparing the "line height" (with my admittedly very simplistic algorithm) against the content height to determine whether or not to render the button. I get the same measurement in all three browsers, so as far as I can tell Safari is just measuring the scroll height of the content differently than in Chrome and Firefox.
I seemingly have to use a min height because the line-clamp property causes the content to collapse to zero in Safari. Setting the min height allows things to work more or less as predicted where the content is more than the user-defined lines to show prop given to the component.
Screenshots of the console logs for the SAME content in each browser:
Firefox:
Chrome:
Safari:
I am trying to show a basic tooltip when the user clicks on an event in the calendar with a few event details but the tooltip gets covered by the next row.
Currently, I'm trying to use the slotPropGetter prop to change the style of a cell to include z-index: -1 and inline-styling the tooltip with z-index: 1000 but to no avail.
Here's my current component:
export default() =>{
const eventStyleGetter = ({ color }) => {
const style = {
backgroundColor: color,
opacity: 0.8,
zindex: "6",
position:"relative",
};
return {
style: style,
};
};
const slotStyleGetter = () =>{
const style = {
position: "relative",
zindex:0,
height:"100px",
}
return{
style: style
}
}
const CalendarElement = (
<Calendar
localizer={localizer}
defaultDate={new Date()}
events={events}
style={{ height: 500 }}
eventPropGetter={(event) => eventStyleGetter(event)}
slotPropGetter={(slot) => slotStyleGetter(slot)}
onSelectSlot={(e) => handleSlotSelect(e)}
selectable
popup
components={{
event: EventPopover,
}}
/>
);
return(
{CalendarElement}
)
}
The issue isn't the cell z-index, but that of your tooltip. What are you using to render your tooltip? Under the hood, RBC has react-bootstrap#^0.32.4, which uses react-overlay#^0.8.0. If you use react-overlay to create your tooltips, you can portal them, which should automatically handle your z-index issue.
The way to correctly implement this is to use Reactstrap/Bootstrap Popover (based on Popperjs) rather than plain CSS. It worked in this case.
I made a toggle component (Accordion to be exact)
I am mapping through an array of objects and listing them like:
{object.map((o) => (
<Accordion key={o.id} title={o.question} className="item">
<div className="text"> { o.answer } <div/>
</Accordion>
))}
It renders something like this:
> Question 1
> Question 2
> Question 3
Now, every time I click a question, it toggles down to show the answer. All this works fine(I used hooks).
I want to be able to change the opacity of all the un toggled elements in this list when ONE of the questions is opened.
So if I open question 2, it becomes the "current item" and the opacity of question 2 and its answer should be 100% and all others(question1 an question3) should dim out or turn 50% opacity.. I am able to do it using :hover using css but that only works on hover.
Basically in theory, I should be able to select an item and remove the base class from all other items except the selected one. I don't know how to do that in reality. Help.
I feel like I'm missing something obvious.
const Accordion = ({ title, children, opened = false }) => {
const [show, setShow] = useState(opened);
const rotation = classnames('icon', {
'rotate': show,
});
const content = classnames('contents', {
'closed': !show,
});
useEffect(() => {
setShow(opened);
}, [opened]);
const toggle = useCallback(() => {
setShow(!show);
}, [show]);
return (
<div className='titleContainer' onClick={toggle}>
<div className={rotations}>
<i className='icon' />
</div>
<h5 className='title'>{title}</h5>
</div>
<div className={content}>{children}</div>
);
};
I finally understand what you mean, I think this is the answer:
const questionColor = (questionIndex, activeQuestion) => {
if (activeQuestion !== null && activeQuestion !== questionIndex) {
return "rgba(0,0,0,0.1)";
} else return "rgba(0,0,0,1)";
};
Working solution here:
https://codesandbox.io/s/cocky-hellman-fxrmc
I want to adjust my textarea height dynamically with Refs and pass it to the state but it don't work correctly.
I created a codesandbox to help you to understand what exactly I want.
https://codesandbox.io/s/ol5277rr25
You can solve this by using useRef and useLayoutEffect built-in hooks of react. This approach updates the height of the textarea before any rendering in the browser and therefor avoids any "visual update"/flickering/jumping of the textarea.
import React from "react";
const MIN_TEXTAREA_HEIGHT = 32;
export default function App() {
const textareaRef = React.useRef(null);
const [value, setValue] = React.useState("");
const onChange = (event) => setValue(event.target.value);
React.useLayoutEffect(() => {
// Reset height - important to shrink on delete
textareaRef.current.style.height = "inherit";
// Set height
textareaRef.current.style.height = `${Math.max(
textareaRef.current.scrollHeight,
MIN_TEXTAREA_HEIGHT
)}px`;
}, [value]);
return (
<textarea
onChange={onChange}
ref={textareaRef}
style={{
minHeight: MIN_TEXTAREA_HEIGHT,
resize: "none"
}}
value={value}
/>
);
}
https://codesandbox.io/s/react-textarea-auto-height-s96b2
Here's a simple solution that doesn't involve refs. The textarea is dynamically adusted using some CSS and the rows attribute. I used this myself, recently (example: https://codesandbox.io/embed/q8174ky809).
In your component, grab the textarea, calculate the current number of rows, and add 1:
const textArea = document.querySelector('textarea')
const textRowCount = textArea ? textArea.value.split("\n").length : 0
const rows = textRowCount + 1
return (
<div>
<textarea
rows={rows}
placeholder="Enter text here."
onKeyPress={/* do something that results in rendering */}
... />
</div>
)
And in your CSS:
textarea {
min-height: 26vh; // adjust this as you see fit
height: unset; // so the height of the textarea isn't overruled by something else
}
You can check the repo. Or you can add the package to your project.
https://github.com/andreypopp/react-textarea-autosize
Also if you really willing to learn how the logic working exactly;
https://github.com/andreypopp/react-textarea-autosize/blob/master/src/calculateNodeHeight.js
There is a source code with all calculations together.