How to convert from functional component to a class component? - reactjs

Hi I'm making a speech recognition for my collaborative whiteboard. My whiteboard component is a class component and I want to put the code of the speech recognition (which is a functional component), in the whiteboard component. But for that I need it to be converted to a class component. I am using library react-speech-recognition
This is the code which needs to be converted:
import React from 'react'
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition'
const Mic = () => {
const { transcript, resetTranscript } = useSpeechRecognition()
if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
return null
}
return (
<div>
<button onClick={SpeechRecognition.startListening}>Start</button>
<button onClick={SpeechRecognition.stopListening}>Stop</button>
<button onClick={resetTranscript}>Reset</button>
<p>{transcript}</p>
</div>
)
}
export default Mic
Can anyone show me how to do it? With the speech recognition function at the transcript and resetTranscript variable makes it harder for me.

You have a problem with your hook useSpeechRecognition, you can't use it inside the class component, you can check the React doc to verify: Hooks FAQ, as an alternative you should use HOC SpeechRecognition:
import React, { Component } from 'react'
import SpeechRecognition from 'react-speech-recognition'
class Mic extends Component {
render() {
const { transcript, resetTranscript, browserSupportsSpeechRecognition } = this.props
if (!browserSupportsSpeechRecognition) {
return null
}
return (
<div>
<button onClick={SpeechRecognition.startListening}>Start</button>
<button onClick={SpeechRecognition.stopListening}>Stop</button>
<button onClick={resetTranscript}>Reset</button>
<p>{transcript}</p>
</div>
)
}
}
export default SpeechRecognition(Mic)

Related

Import a props since an other file for a component ReactJs

i have a question about the range of the props. I would in my App.js just call the component with 2 props (just below) and use those props in my other file "PrimaryButton.js".
function App() {
return (
<div className="App">
<PrimaryBouton Type='primary' Title='Lorem Ipsum'/>
</div>
);
}
export default App;
Here is my other file :
import './PrimaryButton.css';
import React from 'react';
class PrimaryBouton extends React.Component {
render(props) {
return (
<button className={props.Type}>
<span>{props.Title}</span>
</button>
);
}
}
export default PrimaryBouton ;
My Goal is to use the props on App.js to define here the css class of my button and his span.
I don't really know how to "import my props" in this file so if someone can help me thx !
To utilize props in your case, it would look like this:
import './PrimaryButton.css';
import React from 'react';
class PrimaryBouton extends React.Component {
render() {
const { title, type } = this.props;
return (
<button className={type}>
<span>{title}</span>
</button>
);
}
}
export default PrimaryBouton;
I would recommend naming your props lowercase opposed to uppercase. There are instances where you will eventually pass props as uppercase, like passing a component via props, so naming it uppercase generally indicates that.

Ag-grid custom tooltip with functional component

I am looking at ag-Grid's example on creating a custom tooltip.
import React, {Component} from 'react';
export default class CustomTooltip extends Component {
getReactContainerClasses() {
return ['custom-tooltip'];
}
render() {
const data = this.props.api.getDisplayedRowAtIndex(this.props.rowIndex).data;
return (
<div className="custom-tooltip" style={{backgroundColor: this.props.color || 'white'}}>
<p><span>{data.athlete}</span></p>
<p><span>Country: </span> {data.country}</p>
<p><span>Total: </span> {data.total}</p>
</div>
);
}
}
According to ag-Grid's react component page, "If you wish to override the style of this div you can either provide an implementation of the ag-react-container class, or via the getReactContainerStyle or getReactContainerClasses callbacks on the React component:"
How would I go about creating a custom tooltip using a functional component? I am not sure how I would provide an implementation of the getReactContainerClasses callback.
You won't be able to have the public function getReactContainerClasses in a functional component, you'd need to write a class component. If you want to write a functional component, just set the CSS class directly on the container DOM element, similarly to their vanilla JS example. Below is a functional tooltip example which sets the class custom-tooltip.
import React, {Component} from 'react';
export const FunctionalCustomTooltip = (props) => {
props.reactContainer.classList.add('custom-tooltip');
const data = props.api.getDisplayedRowAtIndex(props.rowIndex).data;
return (
<div className="custom-tooltip" style={{backgroundColor: props.color || 'white'}}>
<p><span>{data.athlete}</span></p>
<p><span>Country: </span> {data.country}</p>
<p><span>Total: </span> {data.total}</p>
</div>
);
};
Fully working example:
https://plnkr.co/edit/WHEgtw0YVia1BVP4SVO8?p=preview
You can have public function using React Hooks with useImperativeHandle hook.
export const Component = forwardRef((props: ComponentParams, ref: any) => {
useImperativeHandle(ref, () => {
return {
getReactContainerClasses() {
return ['grid-container'];
},
};
});
}

How to detect when toggle state has been changed in another component in react

I am researching render props in React. I have a small test project build solely for learning. Favorite component toggles the heart from empty to full when the state of "on
" changes. Toggler component handles the state of on and changes /sets state of on with the toggle function. I'm now on FavoriteText component. What I would like this component to do is when state changes in Favorite component to say a full heart, I want the text in the FavoriteText component to reflect the change with text saying "full heart" or "empty heart". I realize this could've easily been done by including the text in Favorite, but again i am looking to acquire more knowledge on render props in React.
FavoriteText.js
import React, {Component} from 'react'
import Toggler from "./Toggler"
function FavoriteText(props) {
return(
<Toggler defaultOnValue={false} render={
(on)=>(
<h1>{on } ? "Full Heart": "Empty Heart"}</h1>
)
}/>
)
}
export default FavoriteText
Toggler.js
import React, {Component} from "react"
class Toggler extends Component {
state = {
on: this.props.defaultOnValue
}
toggle = (e) => {
this.setState(prevState => {
return {
on: !prevState.on
}
})
}
render() {
return (
<div>{this.props.render(this.state.on, this.toggle)}</div>
)
}
}
export default Toggler
Favorite.js
import React, {Component} from "react"
import Toggler from "./Toggler"
function Favorite(props) {
return (
<Toggler defaultOnValue={false} render={
(on, toggle)=> (
<div>
<h3>Click heart to favorite</h3>
<h1>
<span
onClick={toggle}
>
{on ? "❤️" : "♡"}
</span>
</h1>
</div>
)} />
)
}
export default Favorite

how to translate string in a component using react-i18next?

i have a dropdown menu that lists say option1, option2 and option3. i would like to translate these options using react-i18next. I am new to translations and using this framework.
Below is the code,
export default class Example extends React.Component {
render() {
return (
<ParentComponent>
<button type="button">
{this.props.placeholder}
</button>
{this.props.values.map(value => (
<Item
key={value[this.props.value_prop]}
value={value}
on_select={this.change}>
{value[this.props.label_prop]} // i want to
translate this
</Item>
))}
</ParentComponent>
);
}
Could someone provide an idea of how to go about this...or help me solve this. thanks.
react-i18next contains pretty good documentation and they also offer some examples.
You basically need to wrap your componenent in a withTranslation wrapper and use the t props:
import { useTranslation, withTranslation, Trans } from 'react-i18next';
import logo from './logo.svg';
import './App.css';
// use hoc for class based components
class LegacyWelcomeClass extends Component {
render() {
const { t, i18n } = this.props;
return <h2>{t('title')}</h2>;
}
}
const Welcome = withTranslation()(LegacyWelcomeClass);
You haven't posted your full component code, but here's how it should look like:
class CompClass extends Component {
render() {
const { t, i18n } = this.props;
return (
<ParentComponent>
<button type="button">
{this.props.placeholder}
</button>
{this.props.values.map(value => (
<Item
key={value[this.props.value_prop]}
value={value}
on_select={this.change}>
{t(value[this.props.label_prop])} // i want to translate this
</Item>
))}
</ParentComponent>
);
}
}
const Comp = withTranslation()(CompClass);

How to click automatically in a button when user coming to page

import React from "react";
checkClick = () => {
console.log("clicked");
};
class Test extends React.Component {
render() {
return (
<div>
<button id="button" onClick={this.checkClick}>
click
</button>
</div>
);
}
}
export default Test;
How to click automatically on a button when user coming to page?
Here I want to click automatically above button.
I tried with:
document.getElementById("button").click()
which does not work.
You can use a ref which gives you an instance of the dom element, where you can call the click() method.
If you aren't familiar with refs, you can read all about them here: https://reactjs.org/docs/refs-and-the-dom.html
import React, { Component } from 'react'
class Test extends Component {
constructor(props) {
super(props)
this.button = React.createRef()
}
componentDidMount() {
this.button.current.click()
}
checkClick() {
console.log('clicked')
}
render() {
return (
<div>
<button ref={this.button} onClick={this.checkClick}>Click me!</button>
</div>
)
}
}
export default Test
First of all, I do not recommend you to create functions outside of React component class. In your case, you are not able to use it like this.checkClick because the checkClick function is declared outside of your React component.
The second thing, working with real DOM inside of React is basically, let's say, antipattern. React provides virtual DOM and works with it, so, I recommend you to learn about React ref API.
For your case, you can use the lifecycle componentDidMount() method. It is being called (AUTOMATICALLY, for sure) when the component has finished its first render, so, all refs are already available here and all children elements are beind mounted and present in DOM.
import React from "react"
export default class Test extends React.Component {
componentDidMount() {
document.getElementById("button").click()
}
checkClick() {
console.log("clicked!")
}
render() {
return (
<div>
<button id="button" onClick={this.checkClick}>click</button>
</div>
)
}
}
or, using refs
import React from "react"
export default class Test extends React.Component {
componentDidMount() {
this.button.click()
}
checkClick() {
console.log("clicked!")
}
render() {
return (
<div>
<button ref={button => this.button = button} onClick={this.checkClick}>click</button>
</div>
)
}
}
Use componentDidMount for that,
import React from 'react';
class Test extends React.Component {
componentDidMount(){
this.checkClick();
}
checkClick () {
console.log("clicked");
}
render() {
return (
<div>
<button id="button" onClick={this.checkClick}>click</button>
</div>
)
}
}
export default Test;

Resources