React Native what exactly is the <> (empty) component - javascript

In React Native you can encapsulate a set of components in one single <View> (or similar) component. You can also encapsulate a set of components as <> and </>. What are these? Do they just translate to an base View? It's probably not a good practice but it doesn't give a warning and it doesn't crash.

It's the React shortcut for Fragment component.
You can write like this :
import React, { Component } from 'react'
class Component extends Component {
render() {
return <> <ComponentA/> <ComponentB/> </>
}
}
Or without the shortcut and import Fragment component
import React, { Component, Fragment } from 'react'
class Component extends Component {
render() {
return <Fragment> <ComponentA/> <ComponentB/> </Fragment>
}
}
You have to know, you can't use any key or prop with the shortcut syntax.
Here's the official documentation
I hope it helps !

In addition to what He has said, it is used to embed many HTMLElements that you don't what them to be nested into a <div> for example.
For example, you may have this use cases
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
For more explanation you can read this React Official Documentation Fragment

In react <> and </> is just a syntactic sugar for <React.Fragment> . What it basically means is all components should be wrapped in a parent element. So without disturbing the whole schematic design <> provides a wrapper to wrap all your elemnts inside it .
<React.Fragment>
// your code
</React.Fragment>
is same as
<>
// your code
</>
hope it helps

One of the highlights of React v16.2 is Fragments.
If you're working with React projects, you may be familiar with wrapping your child components with <div> or <span> in your render().
Fragment is a first-class component that you can use to wrap your child components and elements in place of <div> or <span> tags. Like so,
render(){
return(
<Fragment>
<h2>Heading</h2>
<ChildA />
</Fragment>
);
}
or
render(){
return(
<React.Fragment>
<h2>Heading</h2>
<ChildA />
</React.Fragment>
);
}
As a shortcut, you can also use empty tags <></> to indicate a fragment. Like so,
render(){
return(
<>
<h2>Heading</h2>
<ChildA />
</>
);
}

If you dont want to put extra divs & spans,
<></> will be nice pick for you
React does the replacement of React.Fragment component there
<></> == <React.Fragment></React.Fragment>

Related

Best way to change CSS in multiple components of the same component in React

I have a component that i'm using 3 times with different data which I am able to complete with the following code;
<div>
<Container className="mt-5">
<Row>
{author_data.map((authors) => {
return (
<Col key={authors.id} className="pe-5 ps-5">
<Author
key={authors.id}
image={authors.image}
author={authors.author}
description={authors.description}
handleClick={(author) => setAuthor(author)}
/>
</Col>
);
})}
</Row>
</Container>
</div>
);
However Im looking to change the CSS on each component once I click on one of the Author components. something like the below using native JS.
document.getElementById("author1").classList.add("addGrayScale");
document.getElementById("author2").classList.add("addGrayScale");
document.getElementById("author3").classList.remove("addGrayScale");
I have used the useState and useContext hooks but I can't seem to get it to work because the Author component will receive the same props. Should I create separate components for each Author? or is there another way to do this.

React – how to render additional component inside another mounted one?

Just wonder are there any approaches to render component in another component in React.
I render a <Scene /> component like this:
import Scene from './Scene';
ReactDOM.render(<Scene/>, document.getElementById('root'));
And at some point I need to render another component <Building /> (for example on onClick) so that it should be inside <Scene />
At the current I'm trying to do so like this:
import Building from './Building';
ReactDOM.render(<Building/>, document.getElementById('fields'));
And this fields container inside this render() method is a child (pretty deep one) of <Scene />
Yes, it renders, it's located inside #fields in HTML, but if I go to React developer tools I see this:
<Scene></Scene>
<Building></Building>
React just rendering <Building> outside of <Scene> and I need quite the opposite.
Unfortunately, conditional rendering isn't the case.
You should only use one ReactDOM.render(), not multiple. It's common to create 1 component (often named <App />) and in that component you create logic. Basically, you create the whole app in Javascript/ReactJS, and you use that line to "load" it into your html.
export class App extends React.Component{
render(){
// It now returns only one component, but this is where you would put your react router
return(
<Scene />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
export class Scene extends React.Component{
render(){
return(
<>
<div> Your normal scene here and if you want <Building /></div>
{ orSomeVariableWhichHasToBeTrue && <Building />}
</>
);
}
}
Also, I suggest trying to follow their Basics tutorial, I think you're missing the way React's intended use. Reading the Doc's again might help for some insights.

react-router v4: triggering a redirect programmatically (without having to render a <Redirect / >)

I'm currently switching my web app to react. The old one is located here.
What I'm trying to do is: when an user enter a player's username into the text field and submit, the app would redirect to the corresponding route (/:username), and the text field is cleared.
In the react version, this is what I'm doing currently:
https://github.com/AVAVT/g0tstats-react/blob/master/src/components/SideBar/SearchBox.js
submit(event){
...
this.setState({
redirect : true
});
...
}
And
render(){
...
{
this.state.redirect && (
<Redirect to={`/${this.state.username}`} push />
)
}
}
Which kinda work. But there are 2 things I don't like about it:
I'm rendering an element in order to redirect. It feels stupid and roundabout. It stinks of potential bug in the future.
I'm stuck with the text field not cleared. Because I if I set state.username to null the <Redirect /> component will not redirect correctly. In fact I don't have any precise control over when the redirection occur (unless I do it in another roundabout way).
I have searched for alternative, but couldn't find one. withRouter doesn't work because <SearchBox /> is not a <Route /> and doesn't receive the history props.
So how can I say "redirect me to that place NOW" in react-router v4?
Here is an example that shows when using the withRouter HOC, the routing props get injected to components even if they are not routed to.
Here is my App.js
class App extends Component {
render() {
return (
<div className="App">
<BrowserRouter>
<div>
<Route path='/test' component={Sample} />
<Sibling />
</div>
</BrowserRouter >
</div>
);
}
}
export default App;
Here is my Sample.js. This is like an example container that is rendering a child.
export default class Sample extends React.Component {
render() {
return (
<div>
<span>{this.props.location.pathname}</span>
<br />
<Nested />
</div>
)
}
}
This component can display information about the current route even without the withRouter HOC since it is being routed to.
Here is my Nested.js.
class Nested extends React.Component {
render() {
return (
<div>
<span>I am nested {this.props.location.pathname}</span>
</div>
)
}
}
export default withRouter(Nested);
My nested component needs the withRouter HOC in order to display the current route.
Finally here is my Sibling.js. (This is like your example where <SearchBox /> is a sibling.)
class Sibling extends React.Component {
render() {
return (
<span>{this.props.location.pathname}</span>
)
}
}
export default withRouter(Sibling);
Here all that is needed is to make sure that the sibling is nested within the router as you can see in my App.js, and then using the withRouter HOC it can display the current pathname.
To clarify: If a component can access the current pathname then it can also change the routes programmatically by doing this. this.props.history.push(some path).
I hope this helps.

Set props on react class

I'm using a third party component.
I have two classes named Parent and Child. In Parent component I use that third party component which accepts a class name as a prop and renders in itself.
So the parent component looks like this:
render(){
return (
<div className="section">
<Select
placeholder={placeholder}
valueComponent={Child}
/>
</div>
);
What I want to do is to pass some props to Child component, but I've always done this like <Child someProp="prop"/>.
Is there any way to pass props to Child component in this manner?
I don't know if the Select library provides a way to do that. In case, you could always use a wrapper component:
// Create a child wrapper component and pass it to Select.
function ChildWrapper(props) {
return <Child {...props} someProp="prop" />;
}
render(){
return (
<div className="section">
<Select
placeholder={placeholder}
valueComponent={ChildWrapper}
/>
</div>
);
}

How to avoid extra wrapping <div> in React?

Today I have started learning ReactJS and after an hour faced with the problem..
I want to insert a component which has two rows inside a div on the page.A simplified example of what I am doing below.
I have an html:
<html>
..
<div id="component-placeholder"></div>
..
</html>
Render function like this:
...
render: function() {
return(
<div className="DeadSimpleComponent">
<div className="DeadSimpleComponent__time">10:23:12</div >
<div className="DeadSimpleComponent__date">MONDAY, 2 MARCH 2015</div>
</div>
)
}
....
And below I am calling render:
ReactDOM.render(<DeadSimpleComponent/>, document.getElementById('component-placeholder'));
Generated HTML looks like this:
<html>
..
<div id="component-placeholder">
<div class="DeadSimpleComponent">
<div class="DeadSimpleComponent__time">10:23:12</div>
<div class="DeadSimpleComponent__date">MONDAY, 2 MARCH 2015</div>
</div>
</div>
..
</html>
The problem that I am not a very happy that React forcing me to wrap all in a div "DeadSimpleComponent". What is the best and simple workaround for it, without explicit DOM manipulations?
UPDATE 7/28/2017: Maintainers of React added that possibility in React 16 Beta 1
Since React 16.2, you can do this:
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
This requirement was removed in React version (16.0), so now you are able to avoid that wrapper.
You can use React.Fragment to render a list of elements without creating a parent node, official example:
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
More here: Fragments
Update 2017-12-05:
React v16.2.0 now fully supports rendering of fragments with improved support for returning multiple children from a components render method without specifying keys in children:
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
If you are using a React version prior to v16.2.0, it is also possible to use <React.Fragment>...</React.Fragment> instead:
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
Original:
React v16.0 introduced returning an array of elements in render method without wrapping it in a div: https://reactjs.org/blog/2017/09/26/react-v16.0.html
render() {
// No need to wrap list items in an extra element!
return [
// Don't forget the keys :)
<li key="A">First item</li>,
<li key="B">Second item</li>,
<li key="C">Third item</li>,
];
}
At the moment, a key is required for each element to avoid the key warning but this could be changed in future releases:
In the future, we’ll likely add a special fragment syntax to JSX that
doesn’t require keys.
You can use:
render(){
return (
<React.Fragment>
<div>Some data</div>
<div>Som other data</div>
</React.Fragment>
)
}
For further details refer to this documentation.
Use [], instead of ()'s to wrap the entire return.
render: function() {
return[
<div className="DeadSimpleComponent__time">10:23:12</div >
<div className="DeadSimpleComponent__date">MONDAY, 2 MARCH 2015</div>
]
}
I created a component to wrap child components without a DIV. It's called a shadow wrapper: https://www.npmjs.com/package/react-shadow-wrapper
This is still required, BUT React now make sure to create elements without creating an additional DOM element.
The extra wrapping needed (normally with a parent div) because Reacts createElement method require a type parameter which is either a tag name string (such as 'div' or 'span'), a React component type (a class or a function). But this was before they introduce React Fragment.
Refer this NEW api doc for createElement
React.createElement : Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), a React component type (a class or a function), or a React fragment type.
here is the official example, Refer React.Fragment.
render() {
return (
<React.Fragment>
Some text.
<h2>A heading</h2>
</React.Fragment>
);
}
I know this question has been answered, you can of course use React.Fragment which doesn't create a node but let's you group stuff like a div.
Additionally if you want to have fun you can implement (and learn lots of things) a React mode that removes the extra div's and for this I really want to share a great video on how you can do it on the react code base itself.
https://www.youtube.com/watch?v=aS41Y_eyNrU
This is of course not something that you would do in practice but it's a good learning opportunity.
You won't be able to get rid of that div element. React.render() needs to return one valid DOM node.
Here is one way to render "transculent" components:
import React from 'react'
const Show = (props) => {
if (props.if || false) {
return (<React.Fragment>{props.children}</React.Fragment>)
}
return '';
};
----
<Show if={yomama.so.biq}>
<img src="https://yomama.so.biq">
<h3>Yoamama</h3>
<Show>
There is workaround too. The below block code generates fragment without the need of React.Fragment.
return [1,2,3].map(i=>{
if(i===1) return <div key={i}>First item</div>
if(i===2) return <div key={i}>Second item</div>
return <div key={i}>Third item</div>
})

Categories

Resources