Reputation: 10779
Why am I getting myRef not defined? I am not sure how to access a component from an external function.
When displayTranscription(transcript)
is called I need to capture the text in the <p>
and concat it to totalText
.
var totalText = '';
const displayTranscription = (transcript) => {
totalText = totalText + myRef.current.text;
console.log('dispalyTranscript called');
return transcript.elements.reduce((a, b) => {
a += ` ${b.value}`;
return a;
}, '');
};
const StreamingCaptionViewer = () => {
const myRef = createRef(null);
const [transcript, setTranscript] = useState(null);
const socket = useSocket('transcript', (data) => {
console.log(`data recieved: ${JSON.stringify(data)}`);
setTranscript(data);
});
const ErrorMessage = {
color: 'red',
fontSize: '13px',
};
return (
<div className='w-full'>
<p ref={myRef} style={ErrorMessage}>
{transcript ? displayTranscription(transcript) : null}
</p>
</div>
);
};
Upvotes: 0
Views: 28
Reputation: 342
Why you don't move the function inside the component and relay on the state transcript
directly without any need to use ref. I'm sure this is the right why to implement this case.
and then to optimize your code convert the function to useMemo
hook to reduce the re-calculations count.
Upvotes: 1