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

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);

Related

Render is not a function e-commerce React component

I use the class component in my Cart.js file but it got the error as "render is not a function". I also try changing it into a function component but it's not working either, please help me to find a way to fix it! Thank you so much!
My sandbox link: https://codesandbox.io/s/why-cant-i-fetch-data-from-a-passed-value-forked-buz0u?file=/src/App.js
Cart component has error, because you're using Consumer from ProductContext in a incorrect way. Change it this code will solve the problem:
import React from "react";
const ProductContext = React.createContext();
export default class Cart extends React.Component {
render() {
return (
<div>
<ProductContext.Consumer>
{(value) => {
return <div>hello</div>
}}
</ProductContext.Consumer>
</div>
);
}
}
Please change your cart component
import React from "react";
const ProductContext = React.createContext();
export default class Cart extends React.Component {
render() {
return (
<div>
<ProductContext.Provider value={null}>
hello
</ProductContext.Provider>
</div>
);
}
}

How to convert from functional component to a class component?

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)

How to send data from one component to another in nextjs

I'm working in nextjs.I have header component and in order to show header in all other pages ,overrided app.js with _app.js .Header has 2 navigation link usersList and users.
Now I want to send data from header component to another page say usersList and users on click of submit in header.How we can achieve that .
I know that we can use context .I'm using class based component don't know weather we can use context.
Is there any other solution to this problem..
Please help
header.js
class HeaderComponent extends Component {
onSearch(event){
//some code
}
render() {
return (
<div className="navbar">
<Input id="search-input" className="text-box" placeholder="Enter name or Email.." onKeyDown={($event)=>this.onSearch($event)} prefix={<Icon type="search" onClick={()=>this.onSearch} ></Icon>}></Input>
</div>
)
}
}
export default HeaderComponent
Layout.js
import React, { Component } from 'react';
import Header from './Header';
class Layout extends Component {
render () {
const { children } = this.props
return (
<div className='layout'>
<Header />
{children}
</div>
);
}
}
_app.js
import React from 'react';
import App from 'next/app';
import Layout from '../components/Layout';
export default class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
}
userList.js
class AppUser extends Component {
render() {
return (
<Table
rowKey={data._id}
columns={this.columns1}
onExpand={this.onExpand}
dataSource={data}
/>
)
}
}
EDIT :
can we achieve it through props
You can use ReactRedux to create a store and have it accessible from all components.
https://redux.js.org/api/store [1]

Pass dynamic value to higher order component

In my code I have to use the same lines of code at different places. So i thought that's the right time to put this code into a kind of base class. I've read about Higher-Order Components which seems to be the way to go and following some examples i ended up with the following code, which is not working. I've tried something around but was not able to get it work.
My HOC:
export interface HocProps {
DynamicId: string
}
const withDiv = (hocProps) => (BaseComponent) => {
return class extend React.Component {
render() {
return (
<div id={ hocProps.DynamicId }>
<BaseComponent />
</div>
);
}
}
}
export default withDiv;
A component to be wrapped by the div:
import withDiv from './MyHoc';
class MyComponent extends React.Component {
render() {
return (
<h3>Some content here</h3>
);
}
}
export default withDiv({ DynamicId: <dynamic value> })(MyComponent);
Another component, that uses MyComponent:
import MyComponent from './MyComponent';
export class OtherComponent extends React.Component {
render() {
return (
<div>
... Some content here ...
<MyComponent DynamicId={ 'id123' } />
</div>
);
}
}
I'd like to pass an id to in OtherComponent. Then in MyComponent this id has to be passed to the HOC as , which is not working. I only can pass static values to the HOC.
I'm new to react and I think i've made same mistake(s).
So my question is: What am i doing wrong and how is it done right?
Maybe there is another/better way for this?
Thanks in advance.
Edit:
I would expect this result:
<div>
... Some content here ...
<div id='id123'>
<h3>Some content here</h3>
</div>
</div>
There are two ways you can use HOCs according to your implementation.
I have created a sandbox, which will help you understand how to use HOCs.
One way is to extract your props out const hocWrapper = Component => props => { // return NewComponent and call it too }. Here you have to call your component while returning.
Other way is to destructure or use the props inside hocWrappers. const hocWrapper = Component => { // return NewComponent, you will receive props inside the newComponent and do what you wish}
Try this
const withDiv = (BaseComponent) => {
class CompWithDiv extends React.Component {
render() {
return (
<div id={this.props.DynamicId}>
<BaseComponent />
</div>
);
}
}
return CompWithDiv ;
}
export default withDiv;
Im not sure how you pass the dynamic values and whats wrong with it. but, you can just create your component like
export interface MyCustomProps {
customProp: string;
}
export interface MyCustomState {
something: string;
}
class MyComponent extends React.Component<MyCustomProps, MyCustomState>{
render(){<div>
... Some content here ...
<div>{this.props.customProp}</div>
</div>}
}
export default MyComponent
and use it in another component like
import MyComponent from './MyComponent';
export class OtherComponent extends React.Component {
render() {
return (
<div>
... Some content here ...
<MyComponent customProp={someDynamicStringValues}/>
</div>
);
}
}
and you can do it recursively

TypeError: robots.map is not a function

I keep getting this error: TypeError: robots.map is not a function.
I reviewed the code several times can't find the bug.
import React from 'react';
import Card from './Card';
// import { robots } from './robots';
const CardList = ({ robots }) => {
return(
<div>
{
robots.map((user, i) => {
return (
<Card
key={i}
id={robots[i].id}
name={robots[i].name}
email={robots[i].email}
/>
);
})
}
</div>
);
}
export default CardList;
App.js
import React, { Component } from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import { robots } from './robots';
class App extends Component {
constructor(){
super()
this.state = {
robots:'robots',
searchfield: ''}
}
render(){
return(
<div className='tc'>
<h1 className=''>RoboFriends</h1>
<SearchBox />
<CardList robots={this.state.robots}/>
</div>
);
}
}
export default App;
I updated the initial code with App.js that calls CardList.
I recently started learning react and I hope to develop an app that lets you search for a user which instantly filters and render the name typed in the search box.
You pass robots as props from App internal state and not from the imported file.
Set the state of App component from the imported robots file
import { robots } from './robots'
class App extends Component {
constructor() {
super()
this.state = {
robots,
searchfield: ''
}
}
render() {
return (
<div className='tc'>
<h1 className=''>RoboFriends</h1>
<SearchBox />
<CardList robots={this.state.robots}/>
</div>
);
}
}
Also using index as React key is a bad practice, You have a unique id in every robot object so use it as key, also read about the map function and how to access the iterated elements
const CardList = ({ robots }) => (
<div>
{robots.map(robot => (
<Card
key={robot.id}
id={robot.id}
name={robot.name}
email={robot.email}
/>
))}
</div>
);
You're passing a string to be mapped, instead pass the robots list of objects and see the result.
These kind of errors are the result of passing something other than a list to be mapped

Resources