How to make flexible width 2d FlatList in react-native - css

I am using react native 0.57. I want to make 2D Grid for non-fixed width and fixed height boxes by using Flatlist. Something like grid show be free to adjust the number of columns according to the screen size. I am unable to implement it.
I can use fixed column but I want my grid to ajust per the device width. The box width can be unpredictable depending upon the text between them. Thanks in advance
Example: In gmail:

You can use flex property , and a width of null.
assuming you have a renderitem function and a max of 4 columns, you will need to have some "dummy items" in your flatlist data
<FlatList
style={{flex:1}}
data={[1,2,3,4,dummy,dummy,3,4,1,2,dummy,dummy]}
renderItem={this.renderItem}
numColumns={4}
/>
renderItem = ({ item, index }) => {
if(item==='dummy'){return <View/>}
return (
<View style={{height:100,width:null,flex:1,backgroundcolor:'red'}}/>
);
};
use flex 1 to fill "dummy" space or flex 1/2 to fill half of the screen , etc.

Related

How to move elements on scroll in React.js?

I am trying to create an E-commerce Store and I'm a beginner in React.JS. What I want is for 5 images to come together on top of eachother when the user scrolls. (so they should move TranslateX on scroll). Previously, on Vanilla Javascript I would have added a window.addEventListener('scroll') and then set a value like value = window.scrollY and then I would have selected the image I wanted to move and simply translateX or Y based on that value.
However, I'm not sure how to do this in React. Where can I set the window event listener? Is there a state needed, or useEffect?
I'm attaching an image so you can clearly see what I am trying to do:
What I have in react is the "Scroll" component which contains 2 divs
-1 div on the left 2/3 flex size containing all the images that should come together
-1 div on the right 1/3 flex size containing the text and the button
inside the left div I have 5 images, and in CSS i've used position absolute to position them on top of eachother (they are all PNGs so they have transparent background).
How would I go about implementing this on my website?
HUGE thanks in advance!
You can save the scrollY in a useState, which you then use to transofrm your images. The window listeners can be loaded inside a useEffect.
It (could) look like this:
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
const handleScroll = () => {
setScrollY(window.scrollY);
};
handleScroll();
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
(You may have to add some ESLint rules if you use it)

How to make text area to fit dynamic content completely without any overflow?

This is an angular app (but anyone with css knowledge can help), where there is a text area with dynamic content.
So as the content item.text changes the text area should grow or shrink according to the content to fit the content perfectly without any overflow.
<textarea [value]="item.text" [placeholder]="item.text ? '' : 'Your Text Here...'" class="font-xl font-bold"></textarea>
// dont worry about the placeholder. you can ignore that.
Currently in my case scrollbar appears & it is not shrinking or growing with the dynamic content.
How can I achieve that?
Or if there is a way to convert a regular html <div> to a textarea, you can suggest that too. But prefers a solution for the above one.
I've tried css rules like, max-content fit-content etc... nothing is working out!
Install npm install ngx-autosize
in html add autosize
<textarea autosize [value]="item.text" [placeholder]="item.text ? '' : 'Your Text Here...'" class="font-xl font-bold"></textarea>
then in appmodule
put in imports: [AutosizeModule ],
Demo
This can't be accomplished with just css, it needs JavaScript that has quite a few corner cases and can be tricky. Such as, pasted input, input populated programatically, auto filled input, handling screen size changes correctly, and on and on, and doing so in a way that is reusable and performs well.
Given all that, I recommend using a lib for this.
I've used angular material's plenty of times with no issues, just add material to your project (can be done via angular CLI with ng add #angular/material) and either import the MatInputModule from #angular/material/input or TextFieldModule from #angular/cdk/text-field (TextFieldModule is quite a bit smaller) to the module where you want to use it, then do:
<textarea cdkTextareaAutoSize cdkAutosizeMinRows="5" [value]="item.text" [placeholder]="item.text ? '' : 'Your Text Here...'" class="font-xl font-bold"></textarea>
you can exclude the cdkAutosizeMinRows option and then it will default to 1 row, but you can use that option to set however many minimum rows you'd like to display. You can also use the cdkAutosizeMaxRows option to make it stop growing at a certain number of rows if you wish, otherwise it will grow indefinitely with the content.
blitz: https://stackblitz.com/edit/angular-4zlkw1?file=src%2Fapp%2Ftext-field-autosize-textarea-example.html
docs: https://material.angular.io/components/input/overview#auto-resizing-textarea-elements
https://material.angular.io/cdk/text-field/overview
You can't change the height of the textarea without Javascript. But you can use an editable div instead. In plain HTML something like this would serve the same purpose as an textarea and will resize automatically based on the content.
<div class="font-xl font-bold" contentEditable>Hello World</div>
If you use a <div> which you can edit then it can grow or shrink accordingly.
<div contenteditable="true">This is a div. It is editable. Try to change this text.</p>
The below will loop over the item and compare height to scrollHeight incrementing the height by lineHeight. Then resets the rows once the height is greater than the scroll height
(function () {
const el = document.querySelector('textarea');
dynamicallyResize(el);
el.addEventListener('change', function () { dynamicallyResize(el); });
})();
function dynamicallyResize(el) {
el == undefined && (el = this.target);
const lineHeight = 16;
let i = el.getAttribute('rows'),
height = Math.ceil(el.getBoundingClientRect().height);
el.style.overflow = 'visible'; //triger redraw
while(height < el.scrollHeight) {
height += lineHeight;
i++;
el.setAttribute('rows', i);
}
el.style.overflow = 'auto';
}
<textarea [value]="item.text" [placeholder]="item.text ? '' : 'Your Text Here...'" class="font-xl font-bold" rows="2">Starting text that exceeds the 2 row limit initially placed on this particular text area.</textarea>

Wrap text of Office UI Fabric DetailsRow

I am trying to get my text to wrap around and display in multiple lines in Office UI Fabric's DetailsRow. At the moment some of my rows that have long text go off the screen, and I would like them to wrap around so the user does not have to scroll to read the entire row.
This is my GroupedList
<GroupedList
items={this._items}
onRenderCell={this._onRenderCell}
groups={this._groups}
selectionMode={SelectionMode.none}
compact={true}
/>
This is my render method for each cell.
_onRenderCell = (nestingDepth, item, itemIndex) => {
return (
<DetailsRow
columns={this._columns}
groupNestingDepth={nestingDepth}
item={item}
itemIndex={itemIndex}
selection={this._selection}
selectionMode={SelectionMode.none}
onClick={() => this.insertComment(item.key, item.link)}
/>
);
};
Any ideas on how to make the text wrap? I am a beginner when it comes to styling.
If you have specific columns whose text are known to require more than "1 line" of text, you can use the isMultiLine property on the column. This is the example that sets isMultiLine to true for a column to wrap the text, which in turn enlarges the height of the corresponding row: "DetailsList - Variable Row Heights".

How to make Material UI TextField less wide when in Table

I've got a Material UI Table.
I build it like this:
tableValues.map((curRow, row) => {
tableRows.push(
<TableRow key={this.state.key + "_row_" + row}>
{curRow.map((cellContent, col) => {
let adHocProps = {...this.props, type:"Text", label:"", value:cellContent}
return (
<TableCell className={classes.tableCell} key={this.props.key + "_row:" + row + "_col:" + col}>
{col===0 && this.props.rowHeaders ?
<div className={classes.header}>{cellContent}</div> :
<Question {...adHocProps} stateChangeHandler={this.handleTableChange("in build")} />}
</TableCell>
)})}
</TableRow>
);
return null;
});
return (
<Table key={this.props.key + "_table"} className={classes.table}>
<TableHead>
<TableRow>
{this.props.colHeaders.map((header) => <TableCell className={classes.tableCell} key={this.props.id + header}><div className={classes.header}>{header}</div></TableCell>)}
</TableRow>
</TableHead>
<TableBody>
{tableRows}
</TableBody>
</Table>
);
The Question is actually a glorified [TextField]2 created thusly:
<div>
<TextField
value={this.state.value}
onChange={this.handleTextChange(this.props.key)}
key={this.props.key}
id={this.props.id}
label={this.props.label}
placeholder={realPlaceholder}
className={classes.textField}
fullWidth
xmlvalue={this.props.XMLValue}
/>
</div>
... and then wrapped in Paper.
The styles are:
tableCell: {
padding: 5,
},
textField: {
padding: 0,
margin: 0,
backgroundColor: "#191",
}
This works, I get the appropriate content in each cell.... but the Question element is way wider than needed, and appear to have a min width and some padding I can't remove.
The table is full-width until you get to a certain point, then notice here:
that when the window is shrunk below a certain level, the table doesn't shrink any further. Acting as if the elements inside have a minimum width.
As a process of investigation, I change the Question element to simply return "Hi". When it does, the table then looks like this:
(which is to say, it condenses nicely... still too much padding on the tops and bottom and right, but WAY better)
So that leads me to believe the issue is with my Question component. I should note this happens on other Questions as well -- they all appear to have a min width when a width is not defined for them... UNLESS they are placed inside a container that has a designated width such as a Material UI Grid. For example, when placed in a `Grid and the window is shrunk, they shrink appropriately:
So why isn't the Table/TableCell also shrinking the TextField like the Grid does? (or: how do I remove the apparent "MinWidth" on my textFields?) Do Material UI TextFields have a minimum width if one isn't otherwise specified?
For what it's worth, I have tried specifying the column widths of the table -- with success when the table is wide, but it still doesn't solve the apparent minimum width issue.
I have also tried changing the Question component to <input type="text" name="fname" /> and still have the same problem. It's interesting that that the Question component is simply "hi" the problem disappears but that when it's an input, it shows up.
I have discovered that the native input fields default width is 20 characters: https://www.w3schools.com/tags/att_input_size.asp
The 'size' property is key here:
Specifies the width of an element, in characters. Default
value is 20
To set the width of the TextField, you must pass properties to the native input field.
If you wish to alter the properties applied to the native input, you
can do so as follows:
const inputProps = {
step: 300,
};
return <TextField id="time" type="time" inputProps={inputProps} />;
For my use case, the following modified the sizes of the TextFields to be 10 characters in size:
<TextField
value={this.state.value}
onChange={this.handleTextChange(this.props.key)}
key={this.props.key}
id={this.props.id}
label={this.props.label}
placeholder={realPlaceholder}
className={classes.textField}
fullWidth
xmlvalue={this.props.XMLValue}
inputProps={{
size: 10
}}
/>
Unfortunately, this is a bit squishy... it neither holds the input field at exactly size nor does it treat it like a minimum size.... There appears to be some heirarchy of sizing in play between GridItems, table Columns, free-flow flex areas, and the actual TextField elements... and I'm not well versed enough to know what always 'wins'.

How do I scale a container UIView's subviews' layout/size as I animate the container UIView?

Goal: to be able to animate a container-view's frame while it's subviews keep their original layout & scale in proportion to their container view.
Scenario:
Elements positioned via constraints/autolayout; within green container.
Green containerView's physical coordinates (frame/bounds) are adjusted per animation.
Members' compression & hugging properties are set to a low priority.
UIView.animateWithDuration(0, animations: {
self.bounds = myBounds
}) {(One) in
UIView.animateWithDuration(1, animations: {
self.frame = myFrame
}) {(Two) in
UIView.animateWithDuration(0.5, animations: {
self.frame = origFrame
// self.center = myCenter
}) {(Three) in
UIView.animateWithDuration(0.2, animations: {
self.frame = distantFrame
})
}
}
}
Here's the original layout:
I would like to have member element scale proportionally with their container view like this:
But the member elements (the one label 'Hello World!') don't adjust accordingly as their green containerView animates to a square in the upper left-hand corner:
How do I keep a UIView's members' layout in proportion to the prevailing their prevailing container view's frame?
Note: This would apply to any type of member (UIView, UITextView, ...etc.); for simple position/layout & transformation (pivot) animations.
In your example, you have a green background view (BG) and a hello world view (HW), and you want HW to scale in proportion to BG.
You can achieve this easily:
Open the Utilities pane in Xcode (top rightmost icon), and the Document outline (bottom left icon of storyboard).
Let’s assume that HW is already centered in BG, i.e. that you already set the alignment constraints for HW center horizontally and vertically in container.
Now, select BG as well as HW in the Document outline, and click the „Pin“ icon bottom right. It will offer the constraints „Equal widths“ and „Equal heights“. Activate both.
After these constraints have been created, open one of them in the Document outline. The utilities pane will then show the Equal Width constraint with the 2 views and a Multiplier field.
In the Multiplier field, you can enter the required proportions for the selected dimension, e.g. 1:3. This will fix the proportion for the selected dimension.
For the other dimension of course analogously. Of course you had then to update the frame of HW.
Here is an example:

Resources