I want to invoke the function good without calling it from a event. It should run as soon as page opened just like in the self invoking javascript function.
Here is an example
import React from 'react';
class App extends React.Component {
good(){
console.log('I was triggered during good')
}
render() {
console.log('I was triggered during render')
return(
<div>
good();
</div>
);
}
}
export default App;
Few Points:
1. You need to use this keyword to call any function from any other function.
2. To put js code inside JSX, we need to use {}.
Write it like this:
import React from 'react';
class App extends React.Component {
good(){
console.log('I was triggered during good')
return <div> Hello </div>
}
render() {
console.log('I was triggered during render')
return(
<div>
{this.good()}
</div>
);
}
}
Check React DOC: https://facebook.github.io/react/docs/introducing-jsx.html
Check these answers for more details:
How does the "this" keyword work?
What do curly braces mean in JSX (React)?
You can also use lifecycle methods as componentDidMount(){} or componentWillMount(){}.
componentWillMount will be triggered before mounting of component and componentDidMount() will be triggered after component has been mounted.
Related
This question already has answers here:
componentDidMount equivalent on a React function/Hooks component?
(11 answers)
Closed 3 months ago.
I have a function which is technically a React Functional Component:
export default function Daw() {
return (
<>
<div>Hello world.</div>
</>
);
}
Of course, my ordinary function cannot have the ReactJS method of componentDidMount(). Since it is not a class which extends React.PureComponent.
I'm using this function inside a ReactJS web app.
export default function Daw() {
componentDidMount() { // ** Cannot use this ReactJS method!?
}
return (
<>
<div>Hello world.</div>
</>
);
}
Question
How can I possibly call componentDidMount() method of ReactJS inside my ordinary function? Is there a way to do it, without converting my function to a class which extends React.PureComponent? Is it possible?
First import useEffect from react
import { useEffect } from "react";
Then use useEffect with an empty dependency array,it is same as componentDidMount()
useEffect(() => { console.log("Mounted"); },[]);
Refer react official documentation for learning all lifecycle methods using useEffect hook:- https://reactjs.org/docs/hooks-effect.html
You're going to need React Hooks! All life-cycle methods we were doing in class components are available in functional components too via React Hooks, even in a better way. Read more about React hooks here: https://reactjs.org/docs/hooks-intro.html
And in this case, the equivalent of componentDidMount is this:
import { useEffect } from 'react'
export default function Daw() {
useEffect(() => {
// Code here will run just like componentDidMount
}, [])
return (
<>
<div>Hello world.</div>
</>
)
}
You can also learn about Effects in React by reading my article: A Beginner’s Guide to Effects in React
You cannot use componentDidMount() (class lifecycle methods) in React functional components. Instead you can use useEffect hook to perform the same operation. Like this:
useEffect(() => {
}, []);
Check here for more info - Similar Question
yes, you can use useEffect hook.
useEffect has the following abilities of class methods .i.e. componentDidMount, componentDidUpdate and componentWillUnmoun.
refer following info from official doc:
https://reactjs.org/docs/hooks-effect.html
I wanted to call the React class component from the JavaScript function which is defined in the another file. Here React Class component having the JSX syntax. Is it possible ?
This is my React Class component defined in the file Example.js
class Example extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
This is my normal JavaScript function defined in the file Normal.js . From this function I wanted to call my React class component. How to call ?
function Calling() {
//From Here I wanted to call React Class component (Example)
}
If we have a React component lets say <App /> that is being rendered in another react component.
Can I have<App doSomething/> so that I can call the function doSomething before it is rendered?
Sorry, to add on the above question - I want to declare doSomething outside in a library so that I can import and call it before the React component <App doSomething/> is rendered.
Here you can read about lifecycle methods. https://reactjs.org/docs/react-component.html#the-component-lifecycle
Time before componentWillMount() was what you are looking for. Now it is deprecated.
According to the diagram that was linked in the react docs page, the place to make that calls can be the constructor
http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
Also you can set an default boolean to false, and in componentDidMount do what you want and set the boolean to true, but in the render method check if that boolean is true and render your things
Yes
In this case doSomething is a prop that can be a function. Using React lifecycle methods you can call this function before the component renders.
From the react docs:
getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update
(Since ComponentWillMount is deprecated).
EX:
class App extends React.Component {
static getDerivedStateFromProps(props) {
props.sayHello();
return null;
}
render() {
console.log("Rendering");
return <div>Hello {this.props.name}</div>;
}
}
class Hello extends React.Component {
sayHello() {
console.log("Hello!");
}
render() {
return <App sayHello={this.sayHello} />;
}
}
ReactDOM.render(
<Hello />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Edit:
It doesn't matter where the doSomething function comes from, you can pass it as a prop, or call it directly.
ESLint is giving me this error on a react project.
Component should be written as a pure function (react prefer/stateless
function)
It points to the first line of the component.
export class myComponent extends React.Component {
render() {
return (
//stuff here
);
}
}
How do I get rid of this error?
Two choices.
Temporarily disable warning
(Untested; and there are multiple ways to do this.)
// eslint-disable-next-line react/prefer-stateless-function
export class myComponent extends React.Component {
...
}
Use a pure stateless component
The return value is what will be rendered (e.g., you're basically writing class-based component's render method:
export const myComponent = () => {
return (
// JSX here
)
}
(Or use non-ES6 notation if that's your thing.)
For components like this with no other supporting logic I prefer the implicit return, e.g.,
export MyComponent = () =>
<div>
// Stuff here
</div>
This is a matter of preference. I would say that you should follow React naming conventions, though, and keep all components starting with an upper-case letter.
ESLint may complain about missing parens around a multi-line JSX expressions, so disable that rule or use parens.
If you need props, they're passed in as the argument to the function:
const MyComponent = (props) =>
<div>
<Something someProp={props.foo} />
</div>
export MyComponent
And you can destructure in the parameter as usual for convenience:
const MyComponent = ({ foo }) =>
<div>
<Something someProp={foo} />
</div>
This can make the implicit return a little easier if you were using local vars. You'll get an ESLint warning about missing PropTypes unless you declare them; since it's not a class you cannot simply use static propTypes in the class, they must be attached to the function (which many people prefer anyway).
Add constructor() like:
exports class myComponent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>Hello</div>
);
}
}
Write your component as a stateless function:
export myComponent = () => { //stuff here };
There are actually two styles of defining components in React: Functional components (which are just functions from props to a React component) and class components.
The main difference between them is that class components can have state and lifecycle methods such as componentDidMount, componentDidUpdate, etc.
Whenever you don't need state of lifecycle methods, you should write your component as a stateless function, as stateless components are in general easier to reason about.
To write a functional component, you write a function that takes a single argument. This argument will receive the component's props. Consequently, you don't use this.props to access the component's props - you just use the function's argument.
If you rely on props, then there is a better (somewhat arguable, as of this writing) way to fix this error without writing out Stateless functions - by writing a PureComponent and using this eslint rule [source]:
"react/prefer-stateless-function": [2, { "ignorePureComponents": true }],
With above rule, the following snippet is valid (since it depends on props)
class Foo extends React.PureComponent {
render() {
return <div>{this.props.foo}</div>;
}
}
React team plans to build optimizations around SFC but they are not there yet. So until that happens, SFCs will not offer any benefits over PureComponents. In fact, they will be slightly worse as they will not prevent wasteful renders.
You will get this error only when your class does not have any life cycle method or constructor.
To solve this either you have to disable the lint property or make it as a pure function or create constructor for the class.
const myComponent = () => {
return (
//stuff here
);
};
export default myComponent;
And in app.js file just import this component as we do for class like
import myComponent from './myComponent.js'
and call as
<myComponent />
It will work for sure.
export class myComponent extends PureComponent {
...
}
If all you're doing is rendering a jsx template, and not declaring state with constructor(props), then you should write your component as a pure function of props, and not use the class keyword to define it.
ex.
export const myComponent = () => (
// jsx goes here
);
you need to add constructor(props)
export class myComponent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
//stuff here
);
}
}
When you set a component or element callback for an event, tutorials and documentation show code like this:
'use strict';
import React from 'react';
let FooComponent = React.createClass({
handleClick(args) {
...
},
render() {
return <div>
<h1>Some title</h1>
<button onClick={this.handleClick}>Click Me!</button>
</div>
}
};
export default FooComponent;
But this handleClick method can be accessed out of this component, if I'd use FooComponent on another component and assign it a reference I can access the handleClick from this other component.
'use strict';
import React from 'react';
import FooComponent from './FooComponent';
let BarComponent = React.createClass(
handleBarComponentClick(e) {
this.refs.fooComponent.handleClick(null);
},
render() {
return <div>
<FooComponent ref="fooComponent" />
<button onClick={this.handleBarComponentClick}>Other click</button>
</div>
}
);
export default BarComponent;
I don't like the fact that I can access that method, which in my opinion should be private or maybe I don't have to worry about it. But to fix that I started using this "good/bad practice" in my projects to avoid that method from being accessed.
'use strict';
import React from 'react';
function handleClick(args) {
...
}
let FooComponent = React.createClass({
render() {
return <div>
<h1>Some title</h1>
<button onClick={handleClick.bind(this)}>Click Me!</button>
</div>
}
};
export default FooComponent;
So it cannot be accessed from outside components.
My doubt is, if what I'm doing is a good or bad practice, or what could be the problems that could happen or not if I continue doing this? Or maybe I don't have to worry to set the event handlers inside the createClass argument?
Thanks in advance :)
Have you checked the Flux pattern? https://facebook.github.io/react/docs/flux-overview.html
In my React apps, this is not a concern. Although I do not define event handlers in a private way, the general rule is that you NEVER call a method on a component. If the subcomponent needs to notify its parent of something, this is accomplished either by a callback transferred from parent to child as a prop or by mutating a global state (via an action) in the child component. If, on the other hand, is the parent that needs to accomplish something on the child, then it changes the props (or the values of such props) on the subcomponent.
Trying to answer your question, I'd say that what you are doing right now (defining the event handlers in a private scope) is ok. But I think is more of a hassle to do such a thing for every handler. I would suggest you to review if the general architecture of your app is in line with what React suggests.