Answer the question
In order to leave comments, you need to log in
How to properly pass functionality between components?
Guys, tell me how to properly organize such functionality on React.
There are two components (functional) - Main and Setting. Main collects several components in itself, including Setting. While in Main I turned on the functionality of switching languages, most likely this is wrong after all. Setting, in turn, includes a switcher (input) that switches app languages (en/ua). Now for the code:
Main.js
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import Setting from '../components/_Setting/Setting';
import { contextArr } from 'App/db'; // перевод словосочетаний app
export default function Main() {
const location = useLocation();
let [lang, setLang] = useState('en');
const chooseLang = (event) => {
setLang(event.target.checked ? (lang = 'ua') : (lang = 'en'));
};
for (let key in contextArr) {
let elem = document.querySelector('.lng-' + key);
if (elem) {
elem.innerHTML = contextArr[key][lang];
}
}
useEffect(() => {
window.location.href = location.pathname + '#' + lang;
}, [location.pathname, lang]);
return (
<main id='main'>
<div className='container df'>
...
<Setting />
...
</div>
</main>
);
}
import Switcher from '../Switcher/Switcher';
export default function Setting() {
return (
<section id='setting'>
<Switcher
id='lang'
title='Language'
title_class='lng-set_subtitle1'
label_lt='English'
label_rt='Українська'
value={lang}
onClick={chooseLang}
/>
</section>
);
}
Answer the question
In order to leave comments, you need to log in
In main.js
<Setting chooseLang={chooseLang} />
In setting.js
import Switcher from '../Switcher/Switcher';
export default function Setting({ chooseLang }) {
return (
<section id='setting'>
<Switcher
id='lang'
title='Language'
title_class='lng-set_subtitle1'
label_lt='English'
label_rt='Українська'
value={lang}
onClick={chooseLang}
/>
</section>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question