component syntax in React - reactjs

I'm a beginner in React, just some questions about component
Let's say I have a component :
function HelloWorld() {
return React.createElement('div', {}, 'Hello World!')
}
so my questions are:
1- HelloWorld is the component name, isn't it?
2- then I have the code below:
ReactDOM.render(
<HelloWorld/>, document.querySelector('#root')
);
what's the syntax of <ComponentName/>? isn't that more sensible to have the render function to be like:
ReactDOM.render(
HelloWorld(), document.querySelector('#root')
);

syntax of ReactDOM.render this :
ReactDOM.render( <Component />, id of DOM element where component will render );
in React there are 2 types of components :
1) functional components (also called stateless components)
2) class components (also called as stateful components
example of functional component :
function HelloWorld() {
return React.createElement('div', {}, 'Hello World!')
}
or
const HelloWorld=()=>{
return (<div>HelloWorld</div>);
}
export default HelloWorld;
example of class component :
class HelloWorld extends React.Component{
render(){
return (<div>HelloWorld</div>);
}
}
so passing component like this :
ReactDOM.render(
HelloWorld(), document.querySelector('#root')
);
is not correct way , in React you use Component as <ComponentName />
so thats why you have to pass like this :
ReactDOM.render(
<HelloWorld/>, document.querySelector('#root')
);

1 - No, that would be the contents (aka "children") of the div tag you are creating. That is <div>Hello World!</div>.
2 - Not sure what the ComponentName you are referring to is. The snippet takes the HelloWorld React component and mounts it to the DOM, which also starts the Reconciliation process.
Also, the purpose of JSX is to have a syntactic sugar that resembles HTML as much as possible. Yes, what you are suggesting is basically what happens behind the scenes (from a pseudo-code point of view), but would defeat the purpose of using JSX.

When react builds your app and run, it will be something like the last example that you gave.
React compile all components to
React.createElement('htmlTag' || someOtherComponent(), ...);
So a lot of people find more easy and productive to write your components using the JSX sintax and just use the build command to compile and bundle the code.

Related

App Component is Getting Props Magically?

I'm checking the code base of a functioning react web-app, and struggling to understand the following from the App.js file:
class App extends React.Component {
render() {
let error = null
if (this.props.error) {
error = <ErrorMessage
message={this.props.error.message}
debug={this.props.error.debug} />
}
return (
<Router>
{this.props.isAuthenticated ?
<div className="holder">
<NavBar
isAuthenticated={this.props.isAuthenticated}
...
Specifically, where does props (this.props.error and this.props.isAuthenticated) come from? Seems like it isn't defined anywhere. In Index.js, it renders the App component without passing in any props ReactDOM.render(<App />, document.getElementById('root'));.
Edit: at the bottom of App.js, it's exported with export default withAuthProvider(App)
and there's a file called AuthProvider.tsx which defines error and isAuthenticated.
Well withAuthProvider is a Higher-Order component. You can learn more about this pattern here. They're actually functions that take a React component as an argument (App in this case) and enhance it with props or logic. withAuthProvider wraps the App component and provides it the error and isAuthenticated props, while it could also implement some authentication logic for you.

can't extend react extended class

I have more than 20 components in my react project. So doing the same thing for every component would be so unwise, so from oop concepts if I create a class with all the functionalities, then I can use it for all the objects I want.
In my case, I want to check if a user is logged in or not. If not redirect to '/login'. Now I have 'NavigationBar' inside each component, where I'm writing some code to redirect or not. But for a few seconds I can see then snap of each components, especially those large ones.
This is not also wise step
So here is what I tried next, created a component named Core extending React.Component, then I extended all component from it, but it gives me error directly.
What is the actual problem here? How this can be solved?
codesandbox.io
just add this line to Child.js
import React from "react";
React doesn't allow creation of component by subclassing defined component, the only way to create component is to extends directly the React.Component class, But react allow you to add extra behavior to defined component by using Higher-Order Components which has purpose to alter defined component by adding wrapper to and existing component
function wrapper(WrappedComponent) {
return class extends React.Component {
render() {
// Here you can add any logic you want
return (<div>
// Here you can add extra code
<h1>Code rendered by wapper</h1>
<WrappedComponent {...this.props} />;
</div>
}
}
}
And you use it like this
import wrapper from './wrapper';
import Child from './Child';
const HigherWrapper = wrapper(Child);
const rootElement = document.getElementById("root");
ReactDOM.render(<HigherWrapper />, rootElement);

Invalid usage of this.props in react component

I'm getting the following error on webpack build and I don't understand why:
SyntaxError: this is a reserved word (11:5)
It occurs inside the Applicatons class at the code which says this.props.apps.map. Its trying to iterate through the passed apps property and create a JSX representation of Application components. I've included the Applications class as the first piece of code and the subsequent code shows how I instantiate the Applications component in a different class. I'm trying to access the props field inside the Applications class which extends the React Component
Here is the Applications class which I am clearly not using React props correctly:
import React from 'react';
import ReactDOM from 'react-dom';
import Application from './Application/Application';
import ErrorBoundary from '../ErrorBoundary/ErrorBoundary';
class Applications extends React.Component {
render(){
let applicationsList=null;
applicationsList = (
{this.props.apps.map((app,index)=>{
return <Application
name={app.name}
desc={app.desc}
changed={(event)=>this.props.changed(event,app.id)}
click={()=>this.props.clicked(index)}
key={app.id}
/>
})}
);
return (
{applicationsList}
)
}
}
And here is the code inside a different react component that instantiates the Applications component.
render(){
let applications=null;
applications = (
<div>
<Applications
apps={this.state.apps}
clicked={this.deleteApplicationHandler}
changed={this.nameChangedHandler}/>
</div>
);
return (<div>{applications}</div>);
}
I'm extremely new to react so i apologize if i missed anything if i did please let me know and ill update the question.
You're trying to use JSX templating syntax outside JSX. Curly brackets are interpreted as defining an object literal. Remove the extra brackets.
render(){
let applicationsList=null;
applicationsList = this.props.apps.map((app,index)=>{
return <Application
name={app.name}
desc={app.desc}
changed={(event)=>this.props.changed(event,app.id)}
click={()=>this.props.clicked(index)}
key={app.id}
/>
});
return applicationsList;
}

What's the point of inject decorator if Provider is said to be already passing all the props down to all the children?

Consider a case:
import { Provider } from 'mobx-react';
import usersStore from './stores/usersStore';
import itemsStore from './stores/itemsStore';
const stores = { usersStore, itemsStore };
ReactDOM.render(
<Provider {...stores}>
<SomeComponent />
</Provider>,
document.getElementById('app')
);
So, doesn't SomeComponent in the sample above already get both usersStore and itemsStore as its props from Provider? Why is the #inject('itemsStore') line in the following sample even required?
#inject('itemsStore') #observer
class SomeComponent extends React.Component {
render() {
return (
<div className="index">
{this.props.itemsStore.items.map((item, index) => {
return <span key={index}>item.name</span>
})}
</div>
);
}
}
Provider is a component that can pass stores (or other stuff) using
React's context mechanism to child components. This is useful if you
have things that you don't want to pass through multiple layers of
components explicitly.
inject can be used to pick up those stores. It is a higher order
component that takes a list of strings and makes those stores
available to the wrapped component.
Provider and inject are abstractions to React context API (which until recently was quite unstable).
The Provider makes data available from components context, while inject HOC provides a simple API to declare what we want out of the context and passes it to the wrapper component.
The same works other libraries like react-redux.

React tutorial not displaying the div

Im a started with Reactjs and built my initial div but for some reason it does not display the div.
Here is the code displayed
helloworld.js content:
React.render(
React.createElement('h1',null,'Hello World')
,document.getElementById('divContainer')
)
Console error:
react.render is not a function.
React version used:
React v15.0.1
Please use ReactDOM.render() function
You need to import React like so:
import React from 'react';
You need to import the library called React. Also, React.render() is deprecated, you need to use ReactDOM.render().
To take a component and render it to the DOM has been a separate library called ReactDOM. You don't use React with render(), you use ReactDOM. In order to use it you also have to import it like so:
import ReactDOM from 'react-dom';
Then you can implement:
ReactDOM.render(App);
But that is not all. You have not shown us the whole code to your component, but you need to instantiate your component before rendering. What you showed seems to be the transpiled version from Babel, but even that seems not quite right, it would look like this:
var App = function App() {
return React.createElement(
"h1",
null,
"Hello World"
);
};
ReactDOM.render(React.createElement(App, null));
And the above code would be based off creating an instance of App.
This is a class: App of a component, it produces instances. To make an instance, you just wrap it in jsx tags like soL <App />.
Last but not least you need to put it in the page or DOM via the second argument which is a target container. When you render the component <App />, produce some HTML into this element that exists in our HTML document, so then your code, going by your transpiled version that you shared here would look like this:
var App = function App() {
return React.createElement(
'h1',
null,
'Hello World'
);
};
ReactDOM.render(React.createElement(App, null), document.querySelector('.container'));

Resources