setTimeout() not waiting in React Native

Gracias anticipadamente,

I´m trying to execute this function only after 15 seconds but it excecutes right away.

Estoy tratando de ejecutar la funcion setTimeout despue de 15 segundos en react native, pero esta se ejecuta ni bien comienza la aplicación.

Now, this component is being mounted around 8 times once the user logs into the application.

Ahora, el componente esta siendo ejecutado 8 veces una vez que se logea el usuario al aplicativo.

I got isFocused function to clear the timeout if it’s being focused, that fixes the times that is executing the function but not the problem of it actually waiting the 15 seconds.

Usé la función isFocused para limpiar el timeout si es que este componente esta siendo enfocado, esto arregla el problema de la multiple ejecución sonbre el mismo componente, pero no el problema que tengo de no esperar los 15 segundo qe especifique.

The goal is for the set timeout to actually wait the 15 seconds I specified if it gets cleared before that then nothing should happen and the application just continues normally.

El objetivo es lograr que el setTimeout realmente espere los 15 segundos, si es que la función se limpia con cleartimeout antes de eso no hay problema porque nada debería pasar. Solo en el evento de que se demoré mas de 15 segundos esto debería aparecer.

Here is the code:

Aquí está el código:

 constructor(props) {     super(props);     this.counter = 0;     this.timeout = null;  } componentDidMount(){     console.log('FIRST WHAT ARE THESE PROOPS', this.props)     this.timeout = setTimeout(this.waiting, 15000); } shouldComponentUpdate(){     if (!this.props.isFocused) {         clearTimeout(this.timeout);         this.timeout = null;     }     return true; } componentWillUnmount() {     clearTimeout(this.timeout);     this.timeout = null; } waiting = () => {     Alert.alert(         'Oops',         'An error ocurred while loading',         [             {                 text: 'OK', onPress: () => {                     console.log('HEY I CAME IN HERE')                     this.props.screen();                     this.props.navigation.goBack();                 }             }         ],         { cancelable: false }     ) } 

El mismo código pero en imagen, the same code but in an image

React component vs HTML component implementation in terms of design and efficiency

Straight to my question, I have a submit button for multiple react pages. It is very simple and it can be done by writing a simple HTML tag. Do I really need to create a react button component for that? I know that the react way is to have us reuse components so I think the later one makes more sense if I am using react.

Office UI fabric react Commandbar 3rd level menu rendering issue

I am using Office UI fabric react commmandbar in Office 365 – SharePoint to display 3 level navigation.It’s showing 1st level then click on it user can see 2nd level and onmouseovercof 2nd level,3rd level is populating. I am having the problem when I am adding href to 2nd level then 3rd level is not getting populated and If I remove the href value then 3rd level menu is populating. Is there any way we can overcome this problem or any alternate setting we can apply to commandbar.

Posição do label no Picker do React Native

Estou utilizando o componente Picker do React Native e ta funcionando, listando, selecionando e tal, só que nn consigo estilizar bem ele, consegui colocar borda, arrumar o tamanho porem o texto que fica dentro dele eu nn consegui mexer, nem no tamanho da fonte e nem a posição que ele vai ficar la dentro, tentei colocar as propriedades flexDirection: 'row', alignItems: 'center', justifyContent: 'center' no style de uma View que fica sobre o Picker, no style do Picker e na propriedade itemStyle do Picker e nenhum destes funcionou, em todos o texto fica na esquerda, nn colado, mas fica pra esquerda e eu queria centralizar ele. Alguem pode me ajudar?

Código:

            <View style={HorariosCommandStyles.containerPickerServicos}>                 <Picker itemStyle={{ paddingLeft: 50, fontSize: 35 }} style={{ width: '90%', height: '100%' }}>                     {this.state.servicos.map(s => <Picker.Item label={s.servico.nome} value={s.servico.id} key={s.id} />)}                 </Picker>             </View>

How to pass the value to multiple(inter) components using React?

Currently working in one of the Drupal 8 project which has React integration. We are using PDB module to integrate React with Drupal.

PDB uses React component as a block which can be enabled for specific pages. I have created two PDB react components for page-1 & page-2.

Both components have a common form which has one text-field and a submit button.

If the user enters some city name in the page-1 form, same value should be pre-filled in page-2 form’s text-field.

I’m facing the challenge to pass the value to multiple(inter) components.

Can anyone have a solution?

React invalid input value

onSubmit = () => {         const {error} = this.state;         const {board, column, onClose} = this.props;         const value = this.columnNameTextField.current.value;         const positionIndex = column.positionIndex;          if (!value.length) {             return this.setState({error: "Поле обязательное"});         }          if (error !== null) {             this.setState({error: null});         }          onClose(() => {             const data = {             name: value,             positionIndex: column.positionIndex         };             if (!isUndefined(board.id)) {                 this.props.updateColumnName(board.id, column.id, data);             }         });     }; 

Input value = column.name идет и он меняется а positionIndex должен быть неизменным передоваться в принципе и правильно уходит но жалуется на массив test

Integrating bootstrap and materialize css in separate React components

I know this is very bad approach when we try to add two different css frameworks in a single project. But for now, due to a project requirement, I need to add bootstrap and materialize css in a project. In root component bootstrap is used, and in child component I will use materialize.

In child component I have included materialize in the following way

import React, {Component} from 'react'; import {findDOMNode} from 'react-dom'; import screenFull from 'screenfull'; import material from 'materialize-css/dist/css/materialize.css'; import './Control.css'; 

but adding this way overlaps bootstrap classes which is obviously not the required behaviour.

I want to limit scope of materialize.css inside the child component only. Can anyone give me a suggestion on this?

Note: Root component was developed before, and create-react-app is not used over there. webpack configuration file has been written manually.

How to convert this Jquery code to React JS?

I have used this Jquery code in a .jsx file within the ComponentDidMount(){}.

But I want to write this in ReactJS. How should I do this?

$  (document).on("mouseenter", ".owl-item", function() {       // $  (this).css('border','5px solid red')       $  (this)         .prevAll(".active")         .addClass("hover-prev");       $  (this)         .nextAll(".active")         .addClass("hover-next");     }); $  (document).on("mouseout", ".owl-item", function() {       $  (this)         .prevAll(".active")         .removeClass("hover-prev");       $  (this)         .nextAll(".active")         .removeClass("hover-next");     }); 

react native renderizado condicional de tabnav

Estoy haciendo una app con react-native, cuando el user se registra se le asigna un rol que cuando la app llega a la home, el tabnavbottom cambia.

Ahora mismo le estoy pasando al componente que renderiza el tabnavbottom por props, pero se me queda atascado en el estado por defecto.

os pongo el código.

import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View} from 'react-native'; import Router from './src/routes/router';  import {Provider} from 'react-redux' import { createStore } from 'redux'; import devToolsEnhancer from 'remote-redux-devtools'; import reducers from './src/redux/reducers'  const store = createStore(reducers, devToolsEnhancer());  class App extends Component { 	constructor(props){ 		super(props)  		this.state = { 			role: store.getState().user.role 		} 	}   	componentWillReceiveProps(nextProps) { 		console.log('nextProps===>', nextProps) 		this.setState({role: nextProps.state.user.role }); 	}   	shouldComponentUpdate(nextProps) { 		console.log('pues entro') 		return true 	} 	render() { 		return ( 			<Provider store={store}> 				<Router role={this.state.role}/> 			</Provider> 		) 	} }  export default App

import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View} from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome';  import UserPaths from './UserPaths'; import TransporterPaths from './TransporterPaths';   class Router extends Component {   	renderByRole(){ 		console.log('KALIMA', this.props.role) 		if(this.props.role === 'user'){ 			return( 				<UserPaths /> 			) 		}else{ 			return ( 				<TransporterPaths /> 			) 		} 	}  	render() { 		return ( 			<View style={{flex:1}}> 				{this.renderByRole()} 			</View> 		) 	} }  export default Router

import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View} from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import { createBottomTabNavigator, createStackNavigator, tabBarIcon } from 'react-navigation';  import I18n from '../i18n/i18n'  //screens common import WelcomeScreen from '../screens/WelcomeScreen'; import LoginScreen from '../screens/LoginScreen'; import SignUpScreen from '../screens/SignUpScreen'; import HomeScreen from '../screens/HomeScreen'; import ProfileScreen from '../screens/ProfileScreen'; //Screens transporter import TransporterShowOrderScreen from '../screens/TransporterShowOrderScreen'; import TransporterOrderCard from '../components/transporter/TransporterOrderCard'; import TransporterOrdinaryListScreen from '../screens/TransporterOrdinaryListScreen';  class TransporterPaths extends Component { 	render(){ 		const TransporterNavigator = createStackNavigator({ 			welcome: { 				screen: WelcomeScreen, 				navigationOptions: { 					header: null 				} 			}, 			login: { 				screen: LoginScreen, 				navigationOptions: { 					header: null 				} 			}, 			signUp: { 				screen: SignUpScreen, 				navigationOptions: { 					header: null 				} 			}, 			transporterShowOrderScreen: { 				screen: TransporterShowOrderScreen, 				navigationOptions: { 					header: null 				} 			}, 			trasnsporterOrderCard: { 				screen: TransporterOrderCard, 				navigationOptions: { 					header: null 				} 			}, 			main: { 				screen: createBottomTabNavigator({ 					userHome: { 						screen: HomeScreen, 						navigationOptions: { 							tabBarLabel: I18n.t('nav.nowSends'), 							header: null, 							tabBarIcon: ({tintColor}) =>(<Icon name="home" size={20} color={tintColor} />) 						} 					}, 					ordinaryList: { 						screen: TransporterOrdinaryListScreen, 						navigationOptions: { 							tabBarLabel: I18n.t('nav.sends'), 							header: null, 							tabBarIcon: ({ tintColor}) => (<Icon name="cubes" size={20}  color={tintColor}/>) 						} 					}, 					userProfile: { 						screen: ProfileScreen, 						navigationOptions: { 							tabBarLabel: I18n.t('nav.profile'), 							header: null, 							tabBarIcon: ({ tintColor}) => (<Icon name="user-circle" size={20}  color={tintColor}/>) 						} 					}, 				},{ 					tabBarOptions: { 						activeTintColor: '#521168', 						inactiveTintColor: '#fff', 						labelStyle: { 							fontSize: 11, 							fontWeight: 'bold' 						}, 					style: { 						backgroundColor: '#d3560e', 						height: (Platform.OS === 'ios') ? 48 : 50 					} 				} 			}) 		}, 		},{ 			navigationOptions: { 				tabBarVisible:  false, 				header: null, 			} 		}) 		return(<TransporterNavigator />) 	} }  export default TransporterPaths;

import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View} from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import { createBottomTabNavigator, createStackNavigator, tabBarIcon } from 'react-navigation';  //screens common import WelcomeScreen from '../screens/WelcomeScreen'; import LoginScreen from '../screens/LoginScreen'; import SignUpScreen from '../screens/SignUpScreen'; import HomeScreen from '../screens/HomeScreen'; import ProfileScreen from '../screens/ProfileScreen'; //screens user import UserNewOrderScreen from '../screens/UserNewOrderScreen'; import UserOrderListScreen from '../screens/UserOrderListScreen'; import UserOrderedListScreen from '../screens/UserOrderedListScreen'; import UserTracingScreen from '../screens/UserTracingScreen'; import UserRatingScreen from '../screens/UserRatingScreen';   class UserPaths extends Component { 	render(){  		const UserNavigator = createStackNavigator({ 			welcome: { 				screen: WelcomeScreen, 				navigationOptions: { 					header: null 				} 			}, 			login: { 				screen: LoginScreen, 				navigationOptions: { 					header: null 				} 			}, 			signUp: { 				screen: SignUpScreen, 				navigationOptions: { 					header: null 				} 			}, 			rating: { 				screen: UserRatingScreen, 				navigationOptions: { 					header: null 				} 			}, 			main: { 				screen: createBottomTabNavigator({ 					userHome: { 						screen: HomeScreen, 						navigationOptions: { 							tabBarLabel: 'Home', 							header: null, 							tabBarIcon: ({tintColor}) =>(<Icon name="home" size={20} color={tintColor} />) 						} 					}, 					userNewOrder: { 						screen: UserNewOrderScreen, 						navigationOptions: { 							tabBarLabel: 'N. Envio', 							header: null, 							tabBarIcon: ({tintColor}) => (<Icon name="plus-square" size={20}  color={tintColor}/>) 						} 					}, 					userOrderList: { 						screen: UserOrderListScreen, 						navigationOptions: { 							tabBarLabel: 'Presupuestos', 							header: null, 							tabBarIcon: ({tintColor}) => (<Icon name="inbox" size={20}  color={tintColor}/>) 						} 					}, 					userOrderedList: { 						screen: UserOrderedListScreen, 						navigationOptions: { 							tabBarLabel: 'Histórico', 							header: null, 							tabBarIcon: ({tintColor}) => (<Icon name="list" size={20} color={tintColor} />) 						} 					}, 					userProfile: { 						screen: ProfileScreen, 						navigationOptions: { 							tabBarLabel: 'Perfil', 							header: null, 							tabBarIcon: ({ tintColor}) => (<Icon name="user-circle" size={20}  color={tintColor}/>), 							style:{backgroundColor:'red'} 						} 					} 				},{ 					tabBarOptions: { 						activeTintColor: '#521168', 						inactiveTintColor: '#fff', 						labelStyle: { 							fontSize: 11, 							fontWeight: 'bold' 						}, 						style: { 							backgroundColor: '#d3560e', 							height: (Platform.OS === 'ios') ? 48 : 50 						} 					} 				}) 			}, 		},{ 			navigationOptions: { 				tabBarVisible:  false, 				header: null, 			} 		}); 		return( 			<UserNavigator /> 		) 	} }  export default UserPaths;

Gracias

React активный класс для функции map

Получается фильтр для календаря делаю через map и там 7 обьектов как сделать что бы при выборе там праздничных дат только праздничные получали класс active и при нажатии на другой фильтр другой обьект становился активный а все остальные теряли класс актив? есть ли пример какой? у меня вечно то все сразу активные то только первый клик(

{ _.map(this.firstRowEventTypes(), (item, key) =>     <button className="event-type-item" onClick={() => this.filterEvents(item.color)} key={key}>     <div className="event-type-circle" style={{backgroundColor: item.color}}/>     <div onClick={ () => this.setState({active: this.state.active === item.color ? null : item.color}) } className={classnames("event-type-name", this.state.active === item.color && 'calendar-filter-active')}>{item.name}</div> </button>     )   }    filterEvents(color) {     const events = [];      this.state.allEvents.map((val) => {         if (val.color === color) {             events.push(val);         }     });      this.setState({...this.state, events}); } firstRowEventTypes() {         return [             {color: '#108aeb', name: 'Заседания', id: '1'},             {color: '#4caf50', name: 'Обучение', id: '2'},             {color: '#87cefa', name: 'Праздники', id: '3'},             {color: '#ff5252', name: 'Корпоративы', id: '4'},             {color: '#ab47bc', name: 'Спорт', id: '5'},             {color: '#e91e63', name: 'Культура', id: '6'},             //color: '#8d6e63', name: 'Другое'},             {color: '#d1d1d6', name: 'Другое', id: '7'},             //{color: '#108AEB', name: 'Корпоративный'},             //{color: '#87cefa', name: 'Гос. праздники'},             //{color: '#e91e63', name: 'Корп. мероприятия'},             //{color: '#8d6e63', name: 'Корп. развитие'},             //{color: '#ffa726', name: 'Спортивный'},         ];     }