실전 TypeScirpt 5

2021. 7. 5. 16:01프로그래밍/Typescript

728x90

어제 React Router코드를 분석을 하다가 다음과 같은 상황을 발견했다.

1. React Hook은 조건문이나 반복문 안에 작성하면 안된다.
2. return 안에서도 조건문을 넣어서 출력 여부를 결정해서는 안된다.

하지만 Hook을 사용하는 컴포넌트를 출력하는 대신 null을 출력해도 위의 조건에 위배되지 않았다.

그래서 다음과 같이 NullWrapper를 만들어 보았다.

import { useState, useEffect } from 'react';

function NullWrapper({ visible, children, props }) {
  return (
    visible 
      ? children(props)
      : null
  )
}

function ComponentA(props) {
  const [a, setA] = useState(0);

  return <div>여기는 A입니다</div>;
}

function App() {
  return (
    <NullWrapper visible={false}>
      <ComponentA />
    </NullWrapper>
  );
}

export default App;

왜냐면 전에는 무조건 호출이 되도록 해야하는줄 알고,
CSS로 display: none처리를 시켰다.

물론 CSS로 처리하는게 더 빠르다고 한다.

https://stackoverflow.com/questions/24502898/show-or-hide-element-in-react

 

Show or hide element in React

I am messing around with React.js for the first time and cannot find a way to show or hide something on a page via click event. I am not loading any other library to the page, so I am looking for ...

stackoverflow.com

이런 방법도 있다는걸 알면 좋을 것 같다.

하지만 여기서 멈출수 없지!
CSS를 적용한 방식을 만들어 봤다.

// App.js
import './App.css';
import ComponentA from './ComponentA';
import React from 'react';

function NullWrapper(props) {
  const { visible, children, ...etc } = props;

  const childrenWithProps = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { ...etc });
    }
    return child;
  });

  return (
    <div className={visible ? "" : "hidden"}>
      {childrenWithProps}
    </div>
  )
}

function App() {
  return (
    <NullWrapper visible={false} abc={1}>
      <ComponentA />
      <ComponentA />
    </NullWrapper>
  );
}

export default App;

// App.css
.hidden {
  display: none;
}

TypeScript 버전

import React, { PropsWithChildren } from "react";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({ 
  visible: { all: 'inherit' },
  hidden: { display: 'none' },
})

const NullWrapper:React.FunctionComponent<{ visible: boolean }> = ({ visible, children, ...etc }) => {
  const classes = useStyles();
  
  const childrenWithProps = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { ...etc });
    }
    return child;
  });
  
  return (
    <div className={visible ? classes.visible : classes.hidden}>
      {childrenWithProps}
    </div>
  );
}

export default NullWrapper;

childrenWithProps 출처

https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children

 

How to pass props to {this.props.children}

I'm trying to find the proper way to define some components which could be used in a generic way: There is a logic

stackoverflow.com

 

'프로그래밍 > Typescript' 카테고리의 다른 글

Typescript로 하는 React Context 잡기술  (0) 2021.09.14
실전 TypeScript - 4  (0) 2021.07.04
실전 TypeScript 2  (0) 2021.07.02
근황 & 실전 TypeScript 1  (0) 2021.07.01
TypeScript - Handbook (Modules)  (0) 2021.06.23