Is it ok to render a React element multiple times? - javascript

Let's say I have a functional component rendering 5 icons.
This can be done like this:
export default const Icons = () =>
<div>
<Icon/>
<Icon/>
<Icon/>
<Icon/>
<Icon/>
</div>;
But it can also be done like this:
const icon = <Icon/>;
export default const Icons = () =>
<div>
{icon}
{icon}
{icon}
{icon}
{icon}
<div/>;
The difference is that in the second case, only one React element is created using React.createElement.
Is it discouraged to render a React element multiple times?
If so, why is that? If not, are there any performance or size benefits to be had by rendering a React element multiple times?

You're thinking it wrongly. Both are the same. There's no difference between them. In the second case, you're just assigning to component <Icon /> and each time you call {icon} will actually call to the component <Icon />.
I would rather choose to use first. Because, I don't need to assign unnecessarily which calls to the component.
Here's what will happen when using second case:
Look for {icon}
Look for assigned component <Icon />
Render <Icon /> component
Here's what will happen when using first case:
Look for <Icon />
Render <Icon /> component

It is ok. You can also map over some array of data that you can use to pass down to your components as props.
const altTags = ['me', 'dog', 'cat'];
const icon = <Icon/>;
export default const Icons = () =>
<div>
{this.altTags.map(tag => <Icon alt={tag} />)}
</div>;

It is ok but is not really efficient from the architectural point of view.If we follow the principles of SOLID development this break a few rules.
From a maintenability and reusability point of view this can be improved.
If you create a property in the component that specify how many icons you want and in the render method you use a loop to iterate and create the icons this code will be much better.

Related

React children count

i have a component like this
<Slider
Arrows
Autoplay
>
<SliderContentMall />
</Slider>
and in SliderContentMall i make a map like this
const SliderContentMall = (props) =>
{
return (
props.Data.map(DataValue =>
{
return (
<TouchableOpacity style={Styles.ImageContainer} onPress={() => {}>
</TouchableOpacity>
)
})
);
}
this map returns 3 object the things is in the slider component when i do
console.log(React.Children.count(this.props.children))
it only return 1 and i need the count of the 3, i cant make the map in the slider directly the map needs to be in the SliderContentMall
React.Children.count is doing what it's intended to do: there's a single child, and that child is a <SliderContentMall>. It's not going to check how many children are underneath that, and in fact it can't since those children havn't been rendered yet. Rendering goes from top down, so while you're rendering the <Slider>, you have not yet rendered the <SliderContentMall>, and thus the various <TouchableOpacity>'s havn't even been thought of yet.
If the slider needs to know how many pieces of data will be rendered, the most straightforward way to do that is as a prop to the slider. For example:
<Slider
Arrows
Autoplay
count={data.length}
>
<SliderContentMall data={data}/>
</Slider>
You are using map function over props.Data instead of props.children.

prevent remount when component is wrapped in parent

I have a component that may or may not be rendered in a wrapper component:
class Video extends Component {
state = { isFullscreen: false }
render () {
const { isFullscreen } = this.state
return (
<View>
{isFullscreen ? (
<Modal>
<VideoView />
</Modal>
) : (
<VideoView />
)}
<Button title='inline' onPress={() => this.setState({ isFullscreen: false })} />
<Button title='fullscreen' onPress={() => this.setState({ isFullscreen: true })} />
</View>
)
}
}
Every time I press inline or fullscreen, the <VideoView /> remounts. This makes it hard to add initialization logic to the componentWillMount method. I can do other checks in my application to make sure it works well, but it feels better to re-use the component that already exists.
Is there a way to recycle the <VideoView />?
Ps My project is in React Native, so I used some syntax / component from RN, but I assume the question goes for normal React projects as well
Try wrapping the component with a wrapper and now toggle the styles for this wrapper based on state change. I guess that should work.
Also if you are imminent on reusing the modal component only, what you can do is define some CSS under a new className on the modal Component that alters the required styling to give an effect that the modal is toggled. Then add remove the className based on the state change.

Reuse React component from render props

I wrote a react component in render props way,it will call children function with 3 react component object ( not sure the name exactly, the variable generated by executing jsx (<div>...</div>) );
<PaginatedTable> Usage example:
<PaginationTable data={data} ...otherprops>
{({ SearchBar, Table, PaginationBar })=>
(<div>
{SearchBar}
{Table}
{PaginationBar}
</div>)
}
</PaginationTable>
with render props, I'm so glad that I can custom these 3 child component object very easily such as rearrange order or adding custom elements between these three.
{({ SearchBar, Table, PaginationBar })=>
(<div>
{PaginationBar}
<h1> my custom search bar text </h1>
{SearchBar}
{Table}
</div>)
}
But now I wish more than arrange order inside , I wish I can move {SearchBar} out of to the same layer of 's sibling 's children such as this picture.
working demo: https://codesandbox.io/s/23q6vlywy
I thought this may be anti-pattern to the unidirectional data flow of React.
Extract {SearchBar} to another independent component then use it as <SearchBar ... /> inside of <ToolBarArea /> is what I learnd from React Doc.
But in this way, I have to do "lifting state up" and write similar function and states already had in <PaginationTable /> like below **text** parts are functions and states already had in <PaginationTable />
class ToolBarArea extends Component{
render(){
return(
<div>
// text
<SearchBar onChange={**this.props.onSearchBarChange**} />
//.... other text or elements
</div>);
}
}
class ContainerArea extends Component {
state={
**searchBarText:'',**
tableData : [{...}, {...}]
}
**onSearchBarTextChange = (event)=>{
this.setState({ searchBarText: event.target.value });
}
filterdTableData = ()=> this.state.tableData.filter(d=>d.name.includes(this.state.searchBarText);
**
}
I really hope there is a way I can simply move the variable {SearchBar} in the render props function out to without knowing is in the parent or parent's sibling or anywhere in the DOM tree.
such as
<ToolBarArea>
{SearchBar} // SearchBar from <PaginationTable />
</ToolBarArea>
Is there a way to reuseonSearchBarTextChange and filtedTableData functions and these **text** codes I already wrote in <PaginationTable /> ?
I believe you hit the nail on the head when you referred to lifting state. If you already wrote a similar function then your best option may be to 'abstract' that function so that it applies to both use cases. You could use a simple flag to differentiate the unique execution each needs. Then finally pass the function down to both components.
If you're adamant about avoiding this approach you could technically get around it by using event listeners to handle data transfer or watch variables in the window but this is for sure an anti-pattern.

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 Specifying Style for Sub-Compoennts

I have the following component:
class Dashboard extends Component {
render() {
return (
<Text>MAIN DASHBOARD</Text>
);
};
}
Which I am declaring as:
<View style={styles.dashboard}><Dashboard/></View>
When I declare my styles I have:
dashboard: {
flex:3
},
Now, assume that I wanted to be able to style different sub-components in different ways, for example having my Dashboard component return two views:
<View class="a"><Text>View A</Text>
<View class="b"><Text>View B</Text>
What I'd like to achieve is a css equivalent of:
Dashboard>View.a - {/*props of views with class 'a' which are children of a dashboard element/*}
Dashboard>View.b - {/* Same but for class b /*}
Is there any way to achieve this?
The React Native style system doesn't really have the concept of classes and cascading styles, as in your example. If you are in control of all the child components, you can simply pass arbitrary style objects to your parent Dashboard component and then pass those to the children:
<Dashboard aStyle={{}} bStyle={{}} />
And in your Dashboard view:
return (
<View>
<AView style={this.props.aStyle} />
<BView style={this.props.bStyle} />
</View>
)
For more flexible theming support, you could also use the styled-components library, which allows you to specify a Theme for a certain subtree of your application, and then consume those theme values in any of the children.
That, however, might be overkill for your use case, and you can get by with a simpler solution.

Categories

Resources