React Context api

Hola tengo un todo list hecho en react pero, me surge una duda con el codigo que implemente. en el provider contuve todos los states propios del todo app como users: [] y name: ” ademas de todas las funciones que tenia el form. mi pregunta sobre esto es ¿es sano colocar el form y los metodos del form dentro del provider? adjunto código:

//provider:

import React from "react";  export const ContextoApp = React.createContext();  class TodoProvider extends React.Component {  constructor(props) {   super(props);    this.state = {     name: "",     users: [],     handleData: this.handleData,     handleSubmit: this.handleSubmit   };  this.handleData = e => {   this.setState({     name: e.target.value   }); };  this.handleSubmit = e => {   e.preventDefault();   const newItem = {     name: this.state.name     };   this.setState({     users: this.state.users.concat(newItem)     });   }; }   render() {    return (     <div>       <form onSubmit={e => this.handleSubmit(e)}>       <label>Nombre</label>       <input value={this.state.name} onChange={e => this.handleData(e)} />       <button>Agregar</button>     </form>      <ContextoApp.Provider value={this.state}>       {this.props.children}     </ContextoApp.Provider>   </div>   );   } }  export default TodoProvider; 

Mi componente consumer sera lista.js este componente sera renderizado en app dentro de los tags de el componente mi provider

import React from "react";  import { ContextoApp } from "./contexto/context-todo";  export class Lista extends React.Component {  render() {   return (   <div>     <h1>lista usuarios</h1>     <ul>       <ContextoApp.Consumer>         {valueState => {           return valueState.users.map((user, index) => {             return <li key={index}>{user.name}</li>;           });         }}       </ContextoApp.Consumer>     </ul>   </div>   );   }  } 

Почему теряется контекст в методе ES6 класса React?

import React, {   Component } from 'react';  export default class Text extends Component {   constructor(props) {     super(props);      this.state = {       isOpened: false,     };   }    toggleOpening() {     this.setState((prevState) => ({       isOpened: !prevState.isOpened     }));   }    render() {      return (             <div onClick = {this.toggleOpening} >                Toggle Opening             </div>     );   } }

При клике на div в консоли выскакивает ошибка ‘this is undefined’. В чистом JS при создании класса, его метод корректно ссылается на экземпляр объекта. Почему так?

How to doCRUD Operations using React and PnP-JS Core on sharepoint lists with SharePoint FrameWork (SharePoint 2016)

I would like to create a webpart(Form) where user can feed the input and those data i have to save it in sharepoint list.

I want to perform CRUD operation using React Framework with pnp.js in SharePoint 2016 onprem.

SPFx React framework pnp.js SharePoint list

Do you have any simple examples I can look at and test on SharePoint 2016 to help me to get familiarized with this new concept.

I have searched in github but i couldnt find the right solution. Please help me.

Using getBoundingClientRect to position React component (x,y position)

I’m using portals in react to render my popovers so they appear above all other content. I have it working but they don’t appear next to the button that triggers them.

I’ve been playing around with getBoundingClientRect() using getBoundingClientRect().top/getBoundingClientRect().bottom and getBoundingClientRect().x/y, but what I noticed is that these values change if you load the page at a different scroll position. This means that everytime you load the page the popovers appear in different places and not below the button like they’re supposed to.

import React from 'react' import { string } from 'prop-types' import ReactDOM from 'react-dom'  import Modal from './Modal.jsx' import classNames from 'classnames'  class PopoverWithModal extends React.Component {   constructor (props) {     super(props)      this.state = {       showModal: false,       showPopover: false     }      this.openModal = this.openModal.bind(this)     this.closeModal = this.closeModal.bind(this)     this.handleClick = this.handleClick.bind(this)      this.domNode = null     this.selector = React.createRef()   }    componentDidMount () {     this.domNode = document.getElementById('popover-root')     const buttonTop = this.selector.current.getBoundingClientRect().y     const buttonLeft = this.selector.current.getBoundingClientRect().x     const styles = {       'top': buttonTop,       'left': buttonLeft,       'display': 'block'     }     console.log(this.selector.current.getBoundingClientRect())     this.setState({       styles     })   }    handleClick () {     this.setState((prevState, props) => {       return { showPopover: !prevState.showPopover }     })   }    openModal () {     this.setState({ showModal: true })   }    closeModal () {     this.setState({ showModal: false })   }    render () {     const { id, buttonText, modalContent } = this.props     const { showPopover, showModal } = this.state     const classesAndStuff = classNames({       'hidden': !showPopover,       'popover': true,       'popover-body': true     })     return (       <React.Fragment>         <button ref={this.selector}         className='btn' tabIndex='0' data-toggle='popover' data-trigger='focus' data-popover-content={`#$  {id}`} data-placement='bottom' onClick={this.handleClick}>{buttonText}</button>         { showPopover && ReactDOM.createPortal(           <div id={id} data-container='body' style={this.state.styles} className={classesAndStuff}>             <div className='popover-trigger-text'>               <p>{modalContent}</p>               <span className='btn' onClick={this.openModal}>Read more</span>             </div>           </div>,           this.domNode         )}         <Modal open={showModal} closeModal={this.closeModal}>           <div className='modal-main'>             <h2>Modal Stuff</h2>             <p>{modalContent}</p>           </div>         </Modal>       </React.Fragment>     )   } }  PopoverWithModal.propTypes = {   buttonText: string.isRequired,   modalContent: string.isRequired }  export default PopoverWithModal 

Trying to make array in react native

I have a problem with make my buttongroup dynamic, i tried a lot but nothing seems to work, can someone help me pleas 🙂

import React from 'react'; import { ButtonGroup } from 'react-native-elements';  export default class WebsiteFilter extends React.Component {     constructor(props) {         super(props);         this.state = {             WebsiteFilter: 3     }; }  updateIndex = ( WebsiteFilter ) => this.setState({ WebsiteFilter })  render() {     const buttons= ['Vergelijkdirect', 'Ivanhoe', 'Bespaarcoach'];     let { WebsiteFilter } = this.state;     return (         <ButtonGroup             textStyle={{ textAlign: 'center', fontSize: 12, }}             onPress={this.updateIndex}             WebsiteFilter={WebsiteFilter}             buttons={buttons}         />     );     } } 

Instead of:

const buttons= ['Vergelijkdirect', 'Ivanhoe', 'Bespaarcoach']; 

I need to display the domain of this array:

[{"id":127,"created_at":"2015-11-02 15:35:11","updated_at":"2016-09-19 11:42:10","deleted_at":null,"customer_id":66,"domain":"http:\/\/vergelijkdirect.com","google_id":"UA-97758230-1","currency_id":1,"root":1,"screenshot":"","integration_date":"2016-09-19 11:42:10"},{"id":283,"created_at":"2017-01-13 16:54:24","updated_at":"2017-01-13 16:54:24","deleted_at":null,"customer_id":66,"domain":"https:\/\/ivanhoe.io","google_id":null,"currency_id":1,"root":0,"screenshot":"","integration_date":null},{"id":327,"created_at":"2017-06-14 19:29:42","updated_at":"2017-06-23 17:29:01","deleted_at":null,"customer_id":66,"domain":"http:\/\/bespaarcoach.vergelijkdirect.com","google_id":"UA-39848260-2","currency_id":1,"root":0,"screenshot":"","integration_date":"2017-06-23 17:29:01"}] 

Want to hide some of the Navigation bar links for some of the react components: React+ React-Router+Typescript

I am a bit new to React. I have a situation where I need to hide some of the navigation bar links in some components where as in other I want to display them. Actually been using react router V4 and typescript.

Need to hide page1 and page2 links when it comes to signup and login pages. Show the links in rest of the components.

Help would be appreciated

Router Code

import * as React from 'react'; import NavBar from './NavBar'; import SignUp from './SignUp'; import Page1 from './Page1'; import Page2 from './Page2'; import Login from './Login'; import { BrowserRouter as Router , Switch , Route} from 'react-router-dom';  const NotFound = () => (     <div><h1>404.. This page is not found!</h1></div> );  export default class App extends React.Component<{}, {}>  {      render() {         return(             <Router>                 <div className='container'>                    <NavBar/>                         <div className='body'>                                 <Switch>                                     <Route exact={true} path='/' component={Login}/>                                     <Route path='/signup' component={SignUp}/>                                     <Route path='/login' component={Login}/>                                     <Route path='/page1' component={Page1}/>                                     <Route path='/page2' component={Page2}/>                                     <Route component={NotFound} />                                 </Switch>                         </div>                     <Footer />                 </div>             </Router>         )     } }  

Navigation Bar Component

import React from 'react'; import { Link } from 'react-router'; export default class NavBar extends React.Component<{}, {}> {     render() {             return (        <nav className="nav">          <div className="container">             <ul className="item-wrapper">                 <li>                    <Link to="/page1">Link 1</Link>                 </li>                 <li>                    <Link to="/page2">Link 2</Link>                 </li>             </ul>           </div>         </nav>       );     } }  

Facing difficulty in initialize i18next react component with fetch response data?

I am using i18next to do the internalization.

Default fetch request used to get a data from server and the language information available in response data. Based on language info the page has to be loaded with corresponding language

import i18n from 'i18next'; import { reactI18nextModule } from 'react-i18next'; import LanguageDetector from 'i18next-browser-languagedetector'; import translationEN from './locales/en/translation.json'; import translationDE from './locales/de/translation.json';  // the translations let language; function sendRequest(resources) {   console.log('resources', resources);   i18n     .use(reactI18nextModule) // passes i18n down to react-i18next     .init(       {         resources,         lng: language,         fallbackLng: 'en',         keySeparator: false, // we do not use keys in form messages.welcome          interpolation: {           escapeValue: false // react already safes from xss         }       },       function() {         fetch('http://localhost:3100/getLang')           .then(data => data.json())           .then(res => {             console.log(res);             language = res.lang;             i18n.changeLanguage(language, (err, t) => {               if (err)                 return console.log(                   'something went wrong loading the language',                   err                 );             });           });       }     );   return i18n; } function i18() {   const resources = {     en: {       translation: translationEN     },     de: {       translation: translationDE     }   };   return sendRequest(resources); } export default i18(); 

Language variable is undefined initially. For the very first time i18n init method setup with “fallbackLng” variable instead of “lng”. After that fetch request goes in callback of init method. That will have the response of language need to used. Then i18n changeLanguage method will help to change language.

I am just wondering how can i execute fetch request prior to i18n initialization. I don’t like the approach of initialize the i18next with some default language first and then moved to different language. When i tried to initialize i18n in then part of fetch request doesn’t works for me.

Is there any alternative way available to execute fetch request first and then setup i18n before exporting the component?

Thanks in advance for any suggestion!

React Как лучше реализовать показ слайдера

Итак создаю мобайл версию сайта и возник вопрос. Есть slick слайдер который показывает доступные квесткомнаты(по урлу rooms) и мне нужно сделать еще 2 таких слайдера для news/ и promotions/ в таске указано ,что слайдер должен быть 1 и в зависимости от урла подгружать массив данных.Но как для меня легче просто создать 3 отдельных слайдера (учитывая ,что фоток не 150 штук в слайдере ,а максимум 5-6) и для них свои стэйты данных .Также стоит учесть ,что у слайдера (допустим который отображает комнаты) есть небольшая логика (типо сортировка,добавления разделителя связь с кнопками) тоесть 3 слайдера будут разными ,а не идентичными(кроме данных) .И вот хотел чтобы стак подсказал,как лучше реализовать это (скорость,качество кода,поддержка и т.д) или мб есть 3 варик как это сделать…