I have the following snippet of code
return (
<InputMask
mask="99:99"
*some other prop*
>
{(inputProps) => (
<Input
{...inputProps}
onSubmit={*Does something*}
/>
</InputMask>)
this is the return of a custom component, my question is regarding the syntax... how can a function be defined inside a component? Is this function being called whenever this component is rendered? What is passed into this function (in this case, how is InputProps passed in and what does it contain)?
As you can deduce, I am quite new to frontend development and react in general so any guidance or reference to any documentation will be of great help!
So firstly a quick definition. Here's some JSX where I'm using children:
<MyComponent>
<b>
This bold element
</b>
And this text are children of MyComponent.
</MyComponent>
Inside MyComponent is a regular render method, except importantly, it also has a props.children that it can do whatever it wants with:
render(){
return <div className="my-component">{this.props.children}</div>;
}
Importantly, children is just a prop like anything else. It can be anything you'd like it to be, including a function. This can be particularly powerful if a component wants to give some information to its unknown children. A nice example is some sort of iterator:
<Loop over={[1,2,3]}>
{item => <span>{item}</span>}
</Loop>
Where the Loop component is calling this.children, as it expects it to be a function:
render(){
// For each item in the 'over' prop, call this.props.children
return this.props.over.map(this.props.children);
}
Essentially this is what you have - in terms of when that function runs and what the inputProps object is, it's entirely up to that InputMask component, but it almost certainly will be running it when it renders.
Related
I am currently learning ReactJS, and i wanted to use fullPageJS. It's working correctly, but there is some of the syntax that i don't quite get.
The component:
function home() {
return (
<ReactFullpage
render={({ state, fullpageApi }) => {
return (
<ReactFullpage.Wrapper>
<div className="section">
<h1>Slide 1</h1>
</div>
<div className="section">
<h1>Slide 2</h1>
</div>
</ReactFullpage.Wrapper>
);
}}
/>
)
}
export default home;
Now my question, what does render={({ state, fullpageApi }) => { return(); }} /> do? I can see that it is a property, but i don't really get what it's use is.
This is a pattern known as a Render Prop. It's a way to decide what to render via some two-way communication between your code and the code in ReactFullpage.
You pass a function in as one of the props. That alone a fairly common thing to do, such as passing in a function to an onClick prop. What's special here is how that function gets used.
While ReactFullpage is rendering, it will call your function. It's basically saying "hey, here's some data (the state and fullPageApi). What would you like me to render based on that data?" Your function then calculates and returns the elements you want it to render. And then ReactFullpage will use those elements in its final output.
For more information on render props, see react's documentation on the pattern
In react, render is a method that tell react what to display( what the DOM should look like) . Return in a method or function is the output of the method or function.
I'm also learning React! But since your question is just JS related, here's your answer.
First, let's put your snippet in pieces.
render={ ({ state, fullpageApi }) => { return (/** HTML */); } }
render= is XML, we con't care about it. It is HTML: you're passing a property to the Component element. The brackets {} indicate that it's JS in the HTML code: it means that you're giving JS values to the element's render property. The remaining JS code that was between the {} is:
({ state, fullpageApi }) => { return (/** HTML */); }
Which is a function! So the render prop takes a function that'll probably get executed later.
This anonymous function takes an object as a parameter, but it destructures it and only uses the state and fullpageAPI props, which makes it possible to use them as variables: instead of writing obj.state, you'd write state, as an example. You can read more about restructuring on the MDN docs. It then returns the XML in the parenthesis.
When using React, what is the difference (and when should each method be applied) when rendering a component?
Does this impact the component lifecycle in any way? Or impact how hooks are run in the component?
Method 1:
class App extends React.Component {
...
function getComponent() {
return <Component />
}
render() {
return this.getComponent()
}
}
Method 2:
class App extends React.Component {
...
render() {
return <Component />
}
}
(Note: The OP has now changed the question, it used to have return {this.getComponent()} in Method 1.)
render in Method 1 is incorrect (well, it was before the edit), it should be:
render() {
return this.getComponent() // No {} wrapper
}
You need the {} within a JSX context, but you're not in a JSX context there. For instance, if you wanted to wrap what this.getComponent returned in a div, you'd use the JSX expression to define the div's children within the JSX defining the div:
render() {
return <div>{this.getComponent()}</div>
}
With the {} sorted out, whether you use Method 1 or Method 2 is up to you. If you have substantial parts of the render that you want to move into their own functions, that's fine. For instance:
render() {
return (
<div>
{this.getHeader()}
{this.getBody()}
{this.getFooter()}
</div>
);
}
...although I think I'd probably argue at that point that without a good counter-argument, the header, body, and footer should probably be components (perhaps function components). But the occasional helper function call like that is fine.
Does this impact the component lifecycle in anyway?
No. It's just a function call within render.
There is no real difference between both. I'd personally use only one render() method as much as possible, then when the method gets too big, extract parts of it into their own method.
I have found this great article by Kent C. Dodds. An extract of the article is:
React doesn't know the difference between us calling a function in our JSX and inlining it. So it cannot associate anything to the Counter function, because it's not being rendered like a component.
This is why you need to use JSX (or React.createElement) when rendering components rather than simply calling the function. That way, any hooks that are used can be registered with the instance of the component that React creates.
With this in mind, it sounds like it's better to use JSX when rendering a component that uses hooks.
I have started working on React recently and understood how refs can be used to get hold of a DOM node. In the React docs, they mention the two approaches of creating Refs. Can you please let me know in what situation a callback ref is better than createRef()? I find createRef to be simpler. Although the docs say "callback refs give you more fine grain control" I can't understand in what way.
Thank you
Besides what jmargolisvt said, one thing I found callback is very interesting that I can set multiple refs in an array so that I can control it better.
Like this:
class A extends React.Component {
constructor(props) {
super(props);
this.inputs = [];
}
render() {
return [0, 1, 2, 3].map((key, index) => (
<Input
key={key}
ref={input => this.inputs[index] = input}
/>)
);
}
}
createRef is returning either a DOM node or a mounted instance of a component, depending on where you call it. Either way, what you have in hand is indeed straightforward as you've noted. But what if you want to do something with that reference? What if you want to do it when the component mounts?
Ref callbacks are great for that because they are invoked before componentDidMount and componentDidUpdate. This is how you get more fine-grained control over the ref. You are now not just grabbing DOM elements imperatively, but instead dynamically updating the DOM in the React lifecycle, but with fine-grained access to your DOM via the ref API.
In terms of use cases, callback refs can do anything createRef can do, but not vice versa. createRef gives us a simplified syntax, but that's it.
Things you can't do with createRef:
React to a ref being set or cleared
Use an externally and internally provided ref on the same React element at the same time. (e.g. you need to measure a DOM element's clientHeight whilst, at the same time, allowing an externally provided ref (via forwardRef) to be attached to it.)
Practically you will see no difference except callback ref returns null before initial rendering.
This answer is a little biased on React-Native but still it is applicable if a React component similar to the following example.
<Animated.View> is a wrapper component for <View> that can be animated.
However if you want to access the <View> directly for something like calling the measure() method, then you can do it like:
interface State {
ref: View;
}
public render() {
<Animated.View ref={(component) => {
if (component !== null) {
this.state.ref = component.getNode();
}
}}
>
...
</Animated.View>
}
Otherwise, you need to do: this.state.ref.getNode().
TL;DR: you have control of what to do with an element or how to store it.
If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn’t matter in most cases.
I want to know if it's an anti-pattern or if it affects the component somehow to do something like this:
render() {
const MyFuncComponent = ({ prop1, prop2 }) => (
// code here
)
return (
<div>
<MyFuncComponent prop1={something} prop2={else} />
</div>
)
}
Yes, this is an anti-pattern for the same reason we shouldn't use a Higher-Order-Component inside of render.
Don’t Use HOCs Inside the render Method
React’s diffing algorithm (called reconciliation) uses component identity to determine whether it should update the existing subtree or throw it away and mount a new one. If the component returned from render is identical (===) to the component from the previous render, React recursively updates the subtree by diffing it with the new one. If they’re not equal, the previous subtree is unmounted completely.
Normally, you shouldn’t need to think about this. But it matters for HOCs because it means you can’t apply a HOC to a component within the render method of a component:
render() {
// A new version of EnhancedComponent is created on every render
// EnhancedComponent1 !== EnhancedComponent2
const EnhancedComponent = enhance(MyComponent);
// That causes the entire subtree to unmount/remount each time!
return <EnhancedComponent />;
}
The problem here isn’t just about performance — remounting a component causes the state of that component and all of its children to be lost.
This means that the new component will appear in the React tree (which can be explored with the react-devtools) but it won't retain any state and the lifecycle methods like componentDidMount, componentWillUnmount, useEffect will always get called each render cycle.
Solutions
Since there are probably reasons for dynamically creating a component, here are some common patterns that avoid the pitfalls.
Define the new component outside
Either in its own file, or directly above the parent component's definition. Pass any variable as props instead of using the parent component's scope to access the values.
const MyFuncComponent = ({ prop1, prop2 }) => <>{/* code here */}</>;
const MyComponent = props => (
<div>
{props.list.map(({ something, thing }) => (
<MyFuncComponent prop1={something} prop2={thing} />
))}
</div>
);
Helper function
A regular function that returns JSX can be defined and used directly inside another component. It won't appear as a new component inside React's tree, only its result will appear, as if it was inlined.
That way, we can also use variables from the enclosing scope (like props.itemClass in the following example) in addition to any other parameters.
const MyComponent = props => {
// Looks like a component, but only serves as a function.
const renderItem = ({ prop1, prop2 }) => (
<li className={props.itemClass}> {/* <-- param from enclosing scope */}
{prop1} {prop2} {/* other code */}
</li>
);
return <ul>{props.list.map(renderItem)}</ul>;
};
It could also be defined outside the component since it's really flexible.
const renderItem = (itemClass, { prop1, prop2 }) => (
<li className={itemClass}>
{prop1} {prop2} {/* other code */}
</li>
);
const MyComponent = props => (
<ul>
{props.list.map(item => renderItem(props.itemClass, item))}
</ul>
);
But at that point, we should just define a React component instead of faking it with a function. Use React in a predictable manner and to its full potential.
Inline the logic
It's really common to inline JSX inside of a condition or a map callback.
const MyComponent = (props) => (
<ul>
{props.list.map(({ something, thing }) => (
<li className={props.itemClass}>
{something} {thing} {/* other code */}
</li>
))}
</ul>
);
If we find ourselves copy-pasting this same inlined JSX everywhere, it might be time to wrap it up in its own reusable component.
I think in general people avoid defining functions in render but according to this blog post it is not neccesarily a bad practice. The blog post focuses on inline event handler functions being defined in render but I would guess it applies to any function defined in render. Defining functions in render means there is the overhead of redfining them each time render is called but that may not make a noticible performance difference depending on your component.
For the particular example you gave I would reccomend not to define another react component in render. If you do define any functions in render they should be cohesive to what render is doing. Defining another component or adding a bunch of functions inside of render can make in unwieldy and hard to understand what the code is doing.
I'm trying to pass a ref of a component to another component. Since string refs are being deprecated I'm using callback refs.
So I have something similar to this:
<One ref={c => this.one = c}/>
<Two one={this.one}/>
The problem is that whenever I try to access this.props.one inside Two I get undefined.
I have even tried this on Two:
componentDidMount(){
setTimeout(()=>{
console.log(this.props.one);
},5000)
}
It seems the problem is that when the prop is created, the ref doesn't exist yet since it's created once One is mounted. But I don't know how to "refresh" the props on Two to get the ref to the mounted component.
So what's the proper way of passing a ref to another component?
Edit
Some users have suggested to encapsulate that logic in a higher component, which in itself renders those other child components.
The problem with that approach is that you can't create reusable logic and you have to repeat the same logic over and over in those encapsulating components.
Let's say you want to create a generic <Form> component which encapsulates the submit logic to your store, error checking, etc. And you do something like this:
<Form>
<Input/>
<Input/>
<Input/>
<Input/>
<SubmitButton/>
</Form>
In this example <Form> can't access the instances (and methods) of the children since this.props.children doesn't return those instances. It returns some list of pseudo components.
So how can you check if a certain <Input/> has detected a validation error without passing a ref?
You have to encapsulate those components in another component with the validation logic. For example in <UserForm>. But since each form is different the same logic has to be copied in <CategoryForm>, <GoupForm>, etc. This is terribly inefficient which is why I want to encapsulate the validation logic in <Form> and pass references of the <Input> components to <Form>.
In general the "ref" feature is an anti-pattern in React. It exists to enable side-effect driven development, however in order to benefit the most from the React way of programming you should try to avoid "refs" if possible.
As for your particular issue, passing a child a ref to it's sibling is a chicken vs. egg scenario. The ref callback is fired when the child is mounted, not during render which is why your example doesn't work. One thing you can try is pushing the ref into state and then reading from state into the other child. So:
<One ref={c => !this.state.one && this.setState({ one: c })}/>
<Two one={this.state.one}/>
Note: without the !this.state.one this will cause an infinite loop.
Here is a codepen example of this working (look at the console to see the sibling ref logged): http://codepen.io/anon/pen/pbqvRA
This is now much simpler using the new ref api (available since React 16 - thanks to perilandmishap for pointing that out).
class MyComponent extends React.Component {
constructor (props) {
super(props);
this.oneRef = React.createRef();
}
render () {
return (
<React.Fragment>
<One ref={this.oneRef} />
<Two one={this.oneRef} />
</React.Fragment>
}
}
}
You would consume the prop in Two like:
this.props.one.current
A few things of note with this approach:
The ref will be an object with a current property. That property will be null until the element/component is mounted. Once it's mounted, it will be the instance of One. It should be safe to reference it once <Two /> is mounted.
Once the <One /> instance is unmounted, the current property on the ref returns to being null.
In general, if you need to pass a reference to something that may not be set at call time, you can pass a lambda instead:
<One ref={c => this.one = c}/>
<Two one={() => this.one}/>
and then reference it as
this.props.one()
If it has been set when you call it, you'll get a value. Before that, you'll get undefined (assuming it hasn't otherwise been initialized).
It bears noting that you won't necessarily re-render when it becomes available, and I would expect it to be undefined on the first render. This is something that using state to hold your reference does handle, but you won't get more than one re-render.
Given all that, I would recommend moving whatever code was using the ref to One in Two up into the component that is rendering One and Two, to avoid all the issues with both this strategy, and the one in #Carl Sverre's answer.