I’m creating a simple text editor with features like predictive texting, autocorrection etc. I’m trying to change the format of parts of the user’s input that are within quotations but for some reason the react component keeps showing [object Object] instead of rendering the JSX element. I’m definitely doing something wrong. Any and all help is deeply appreciated
Here’s the function handling this feature
import React from "react"
export default function HandleMonospace(ref, setText){
let text = ref
if(text){
const arraytext= text.split(' ')
let newText= arraytext.map((item)=>{
if(/"[^"]+"/.test(item)){
let moditem= item.split('')
moditem.splice(0, 1)
moditem.splice(moditem.length-1, 1)
moditem=moditem.join('')
return <code>{moditem} </code>
}
else{
return `${item} `
}
})
newText=newText.join('')
setText(newText)
}
}
here, ref represents ref.current.innerHTML
the component being rendered to, is contentEditable
for
Today seems to be a "good" day because the sky is somewhat "clear"
it renders
Today seems to be a [object Object]day because the sky is somewhat [object Object]
I’ve tried switching datatypes
Deferring from using state variables to store and show the input
Using textarea element
2
Answers
The issue is newText is supposed to return an array but the else block is trying to add a space to it.
It’s the
join()
that causing the[object Object]
.If you wrap your
moditem
in a<code>
block, you can’t dojoin()
since that will convert it to a string, resulting in the[object Object]
.Since React can render arrays, just remove the
join()
and render the array returned byHandleMonospace
Small demo:
<code>
block to make it more clear