Skip to content

Instantly share code, notes, and snippets.

@just806me
Created July 2, 2020 16:26
Show Gist options
  • Save just806me/367948b7dc2a842c189f742c97adff3b to your computer and use it in GitHub Desktop.
Save just806me/367948b7dc2a842c189f742c97adff3b to your computer and use it in GitHub Desktop.
Using Action Text from React App
/*
* We need to override trix.css’s image gallery styles to accommodate the
* <action-text-attachment> element we wrap around attachments. Otherwise,
* images in galleries will be squished by the max-width: 33%; rule.
*/
.trix-content .attachment-gallery > action-text-attachment,
.trix-content .attachment-gallery > .attachment {
flex: 1 0 33%;
padding: 0 0.5em;
max-width: 33%;
}
.trix-content .attachment-gallery.attachment-gallery--2 > action-text-attachment,
.trix-content .attachment-gallery.attachment-gallery--2 > .attachment,
.trix-content .attachment-gallery.attachment-gallery--4 > action-text-attachment,
.trix-content .attachment-gallery.attachment-gallery--4 > .attachment {
flex-basis: 50%;
max-width: 50%;
}
.trix-content action-text-attachment .attachment {
padding: 0 !important;
max-width: 100% !important;
}
import React, { useState, useRef } from 'react'
import ReactDOM from 'react-dom'
import 'trix'
import 'trix/dist/trix.css'
import '@rails/actiontext'
import './index.css'
const DIRECT_UPLOAD_URL = 'http://localhost:3000/api/direct_uploads'
const BLOB_URL_TEMPLATE = 'http://localhost:3000/rails/active_storage/blobs/:signed_id/:filename'
function App() {
const [post, updatePost] = useState({ content: { editable_html: '', displayable_html: '' } })
const inputRef = useRef(null)
async function handleSubmit() {
console.log('ref', inputRef)
console.log('content', inputRef.current.value)
const response = await fetch('http://localhost:3000/messages', {
method: 'POST',
body: JSON.stringify({ message: { content: inputRef.current.value } }),
headers: { 'Content-Type': 'application/json' }
})
updatePost(await response.json())
console.log('success')
}
return (
<>
<div>
<h1>Display</h1>
<div class="trix-content" dangerouslySetInnerHTML={{ __html: post.content.displayable_html }} />
</div>
<div>
<h1>Edit</h1>
<input type="hidden" id="trix-input" value={post.content.editable_html} ref={inputRef} />
<trix-editor data-direct-upload-url={DIRECT_UPLOAD_URL} data-blob-url-template={BLOB_URL_TEMPLATE}
class="trix-content" input="trix-input" />
<button onClick={handleSubmit}>Submit</button>
</div>
</>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment