React.js note #7

Yechan Jeon·2021년 12월 20일
0

React dev

목록 보기
7/18
post-thumbnail

Fragments, Portals & Refs


1. JSX limitaion

When we return several jsx elements in component, it will occur error because adjacent JSX elements must be wrapped in an enclosing tag.
The clear reason of that error is we can return several things simultaneously in javscript either.
It is wrapping the entire content with one div tag pair to solve this problem simply.

However, While we're working with this methods, we will make a lot of meaningless 'div' elements and this is not a good idea in programming.
Then what is the ideal solution?

2. Solving JSX limitation

That is making an wrapper component.
If we use props.children, we can print child component as itself.

  • wrapper.js
const Wrapper = (props) => {
  return props.children;
};

export default Wrapper;
  • a child component
return (
    <Wrapper>
      ... some code
    </Wrapper>
  );

3. React Fragments

Creating Wrapper component is quite a clear way, so there is already react built-in component '<React.Fragment>' or '<> - empty'
This two syntaxes exactly work same way.

4. React Portals

This also help us to write cleaner code.
For example, Regarding to modal,side-drawers and other dialogs component, we might add that component in our root and show it as boolean state changes. But this is now ideal structure. It is an overlay to the entire page after all.
With portal's help,Not only we can leave JSX code as it is, But also we can change how it would be rendered.

5. Portals example

  1. you need a place for component to port
  2. and then let the component know that it should port to that place.

To give a place for component, Go to public/index.html and create another element for that component

<div id="backdrop-root"></div>
<div id="overlay-root"></div>
<div id="root"></div> <- this is our original root

Then go to component which you wanna move to somewhere and import react-dom.
import ReactDOM from "react-dom";
Create each JSX elements outside of whole component

const Backdrop = (props) => {
  return something;
};
const ModalOverlay = (props) => {
  return something;
};

//whole component 
const ErrorModal = (props) => {
  return (
    <>
      {ReactDOM.createPortal(
        <Backdrop onConfirm={props.onConfirm} />,
        document.getElementById("backdrop-root")
      )}
      {ReactDOM.createPortal(
        <ModalOverlay
          title={props.title}
          message={props.message}
          onConfirm={props.onConfirm}
        />,
        document.getElementById("overlay-root")
      )}
    </>
  );
};

As you can see, in wrapper, we create portal, give it our elements, and then send it our pre-made places.

Refs

Ref is also one of many react hooks.
Especially When we handle input data, it is quite a useless way of tracking every input value.
Instead of doing that, we can jus refer to that real dom node (Real dom node mean it is not a temporary value or virtual things. It is real document node)
import React, { useState, useRef } from "react";

const nameInputRef = useRef(); // argument is initial value
Then make a prop named 'ref'
<input id="username" type="text" ref={nameInputRef} />

Then your ref object create '.current' property and you can read them in console.

However, If you are using a cutom component and you wanna get value from a child component of that custom component, Go to that child component and use React.forwardRef()

  • custom component
const inputRef = useRef();
<Input
        ...some code
        ref={inputRef}
      />
  • child component
import classes from "./Input.module.css";
import React from "react";

const Input = React.forwardRef((props, ref) => {
  return (
    <div className={classes.input}>
      <label htmlFor={props.input.id}>{props.label}</label>
      <input {...props.input} ref={ref} />
    </div>
  );
});

export default Input;

Uncontrolled vs controlled

Regarding to input, When we use state, we tracked every input of user and feed the data again to input as a 'value' prop(controlled).
However, with ref hooks, we just read the data from real DOM node(uncontrolled).

Ref : React - The complete guide

profile
방황했습니다. 다시 웹 개발 하려고요!

0개의 댓글