diff --git a/src/App.jsx b/src/App.jsx index 6b04285..4b597f0 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,4 +1,4 @@ -import { useState, useCallback, useEffect } from 'react' +import { useState, useCallback } from 'react' import './App.css' import Chat from './chat' import Bubble from './bubble' @@ -17,13 +17,6 @@ function App() { } }, [newMessage, messages]) - useEffect(() => { - const el = document.querySelector('.bubble.input > div') - if (el) { - el.focus() - } - }, []) - return (
diff --git a/src/bubble-input.jsx b/src/bubble-input.jsx index 4f4b10a..892ab4b 100644 --- a/src/bubble-input.jsx +++ b/src/bubble-input.jsx @@ -1,8 +1,9 @@ -import React, { useCallback, useState } from 'react' +import React, { useCallback, useState, useRef, useEffect } from 'react' import './bubble-input.css' import ContentEditable from './content-editable' const BubbleInput = ({ onChange, onSubmit, value }) => { + const refEditable = useRef() const [submitted, setSubmitted] = useState(false) const handleChange = useCallback( @@ -25,7 +26,15 @@ const BubbleInput = ({ onChange, onSubmit, value }) => { }, [onSubmit] ) - console.log('value:', value) + const handleBlur = useCallback(() => { + const { current: elDiv } = refEditable + if (elDiv) { + elDiv.focus() + } + }, [refEditable]) + + useEffect(() => handleBlur(), [handleBlur]) + return (
{ }`} >
diff --git a/src/content-editable.jsx b/src/content-editable.jsx index efde452..ba3562a 100644 --- a/src/content-editable.jsx +++ b/src/content-editable.jsx @@ -1,17 +1,14 @@ import * as React from 'react' class ContentEditable extends React.Component { - constructor(props) { - super(props) - this.refElement = React.createRef() - } render() { + const { innerRef } = this.props return (
{ - const { current: div } = this.refElement + const { current: div } = this.props.innerRef var value = div.innerText if (this.props.onChange && value !== this.lastValue) { this.props.onChange({ @@ -42,6 +39,14 @@ class ContentEditable extends React.Component { const { onKeyDown } = this.props onKeyDown && onKeyDown(e) } + + handleBlur = e => { + this.emitKeyDown(e) + const { onBlur } = this.props + onBlur && onBlur(e) + } } -export default ContentEditable +export default React.forwardRef((props, ref) => { + return +})