0%

React-draft-wysiwyg에서 custom button 생성 및 설정하기

Default code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class CustomOption extends Component {
static propTypes = {
onChange: PropTypes.func,
editorState: PropTypes.object,
};

addStar: Function = (): void => {
const { editorState, onChange } = this.props;
const contentState = Modifier.replaceText(
editorState.getCurrentContent(),
editorState.getSelection(),
'⭐',
editorState.getCurrentInlineStyle(),
);
onChange(EditorState.push(editorState, contentState, 'insert-characters'));
};

render() {
return (
<div onClick={this.addStar}>⭐</div>
);
}
}

class 컴포넌트에서 함수형 컴포넌트로 리팩토링

👇

함수형 컴포넌트

  • 화살표 함수로 정의한 함수형 컴포넌트 내 메소드와 같이 한 단위의 함수인 addStar 을 설정하고, 반환하는 컴포넌트에 이를 onClick 의 속성으로 설정한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const CustomOption = ({
currentEditorState,
...props
}: CustomOptionProps) => {
const addStar = () => {
const currentContentState =
currentEditorState &&
Modifier.replaceText(
currentEditorState.getCurrentContent(),
currentEditorState.getSelection(),
'⭐',
currentEditorState.getCurrentInlineStyle(),
);
currentEditorState &&
currentContentState &&
props.onChange(
EditorState.push(
currentEditorState,
currentContentState,
'insert-characters',
),
);
};

return (
<OptionButton aria-hidden="true" onClick={addStar} onKeyDown={addStar}>

</OptionButton>
);
};
  • onChange 를 받기 위해 React Component를 extend한 인터페이스를 설정한다.
1
2
3
interface CustomOptionProps extends ComponentProps<React.ElementType> {
currentEditorState: EditorState | undefined;
}
  • 그리고 최종적으로, 이를 기존의 Editor에 옵션으로 넣어줘야 한다.
1
2
3
toolbarCustomButtons={[
<CustomOption currentEditorState={editorState} />,
]}

기타 eslint를 위한 설정

1
click-events-have-key-events
  • event에 key를 바인딩해야 안전함 (event 발생할 방법이 따로 없는 경우 key 사용)
1
aria hidden
  • event이므로 accessibility 속성을 기본적으로 설정해야 한다.