Error: Text strings must be rendered within a <Text> component, occurs in android but works fine on web - react-native

My code is working fine on web browser. But when I run it on the cell phone, it shows the error as shown in image. The error is pointed towards the div tags. Got stuck on the error for couple of hours. Also wrapped the div tags with and but none working for me. Any help would be highly appreciated. Here is the code:
import React, { Component } from 'react';
import paginate from 'paginate-array';
import { View,Text,TouchableOpacity,StyleSheet,FlatList,Platform,ActivityIndicator} from 'react-native';
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
size: 5,
page: 1,
currPage: null
}
this.previousPage = this.previousPage.bind(this);
this.nextPage = this.nextPage.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
fetch(`https://jsonplaceholder.typicode.com/todos`)
.then(response => response.json())
.then(todos => {
const { page, size } = this.state;
const currPage = paginate(todos, page, size);
this.setState({
...this.state,
todos,
currPage
});
});
}
previousPage() {
const { currPage, page, size, todos } = this.state;
if (page > 1) {
const newPage = page - 1;
const newCurrPage = paginate(todos, newPage, size);
this.setState({
...this.state,
page: newPage,
currPage: newCurrPage
});
}
}
nextPage() {
const { currPage, page, size, todos } = this.state;
if (page < currPage.totalPages) {
const newPage = page + 1;
const newCurrPage = paginate(todos, newPage, size);
this.setState({ ...this.state, page: newPage, currPage: newCurrPage });
}
}
handleChange(e) {
const { value } = e.target;
const { todos, page } = this.state;
const newSize = +value;
const newPage = 1;
const newCurrPage = paginate(todos, newPage, newSize);
this.setState({
...this.state,
size: newSize,
page: newPage,
currPage: newCurrPage
});
}
render() {
const { page, size, currPage } = this.state;
return (
<div>
<div>page: {page}</div>
<div>size: {size}</div>
<div>
<label for="size">Size</label>
<select name="size" id="size" onChange={this.handleChange}>
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
</select>
</div>
{currPage &&
<ul>
{currPage.data.map(todo => <li key={todo.id}>{todo.title}</li>)}
</ul>
}
<button onClick={this.previousPage}>Previous Page</button>
<button onClick={this.nextPage}>Next Page</button>
</div>
)
}
}
export default TodoList;

What I came to know is you want an infinite list, and also you are going towards wrong direction. You are using react instead of react-native. Try using this:
import React, {Component} from 'react';
import {View, Text, FlatList, Image} from 'react-native';
import {Card} from 'react-native-elements';
import axios from 'axios';
class Users extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
page: 1,
error: null,
};
}
componentDidMount() {
this.fetchUsers(this.state.page);
}
fetchMoreUsers = () => {
this.setState(
prevState => ({
page: prevState.page + 100,
}),
() => {
this.fetchUsers();
},
);
};
fetchUsers = () => {
const {page} = this.state;
axios
.get(`https://api.github.com/users?since=${page}&per_page=10`)
.then(response => {
this.setState({
users: this.state.users.concat(response.data),
});
})
.catch(error => {
this.setState({error: error});
});
};
render() {
return (
<FlatList
contentContainerStyle={{
backgroundColor: '#FBFBF8',
alignItems: 'center',
justifyContent: 'center',
marginTop: 15,
}}
data={this.state.users}
keyExtractor={user => user.id.toString()}
onEndReached={this.fetchMoreUsers}
onEndReachedThreshold={0.5}
initialNumToRender={10}
renderItem={({item}) => (
<View
style={{
marginTop: 10,
}}>
<Card>
<Image
style={{width: 200, height: 100}}
source={{uri: item.avatar_url}}
/>
<Text>{item.login}</Text>
</Card>
</View>
)}
/>
);
}
}
export default Users;

Related

How to load contact details into multi select drop down in react native?

I am creating a react native app to load phone book contacts to my app using this library. I loaded contact correctly in my app. Now I wanted to load these contact details in to multi select drop down. I used react-native-multiple-select to load contact using this library. But I am not be able load contact into this library.
The UI that I need to load contact details.
This is what I tried,
import React, {Component} from 'react';
import {
View,
Text,
TouchableOpacity,
FlatList,
ActivityIndicator,
Image,
TextInput,
PermissionsAndroid,
Platform,
Modal,
TouchableHighlight,
Alert,
} from 'react-native';
import ContactsLib from 'react-native-contacts';
import {styles} from '../src/HomeTabs/ContactStyles';
import PropTypes from 'prop-types';
import {Header} from 'react-native-elements';
import MultiSelect from 'react-native-multiple-select';
//Import MultiSelect library
export class Tab2 extends Component {
constructor(props) {
super(props);
this.state = {
contactList: [],
selectedContact: [],
text: '',
isLoading: true,
show: false,
modalVisible: false,
};
this.arrayholder = [];
}
async componentDidMount() {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
title: 'App Contact Permission',
message: 'This App needs access to your contacts ',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.getListOfContacts();
this.showconsole();
} else {
this.setState({isLoading: false});
this.getOtherContacts();
}
} catch (err) {
this.setState({isLoading: false});
}
} else {
ContactsLib.checkPermission((err, permission) => {
if (permission === 'denied') {
this.setState({isLoading: false});
this.getOtherContacts();
} else {
this.getListOfContacts();
}
});
}
}
// Mics Method
getOtherContacts = () => {
const {otherContactList} = this.props;
const arrFinal = [];
if (otherContactList.length > 0) {
otherContactList.map(listItem => {
arrFinal.push(listItem);
});
}
arrFinal.map((listItem, index) => {
listItem.isSelected = false;
listItem.id = index;
});
this.setState({contactList: arrFinal, isLoading: false});
this.arrayholder = arrFinal;
};
getListOfContacts = () => {
const {otherContactList} = this.props;
const arrFinal = [];
ContactsLib.getAll((err, contacts) => {
if (err) {
throw err;
}
contacts.map(listItem => {
arrFinal.push({
fullname: listItem.givenName + ' ' + listItem.familyName,
phoneNumber:
listItem.phoneNumbers.length > 0
? listItem.phoneNumbers[0].number
: '',
avatar: listItem.thumbnailPath,
});
});
if (otherContactList.length > 0) {
otherContactList.map(listItem => {
arrFinal.push(listItem);
});
}
arrFinal.map((listItem, index) => {
listItem.isSelected = false;
listItem.id = index;
});
this.setState({contactList: arrFinal, isLoading: false});
this.arrayholder = arrFinal;
});
};
getSelectedContacts = () => {
const {selectedContact} = this.state;
return selectedContact;
};
checkContact = item => {
const {onContactSelected, onContactRemove} = this.props;
let arrContact = this.state.contactList;
let arrSelected = this.state.selectedContact;
arrContact.map(listItem => {
if (listItem.id === item.id) {
listItem.isSelected = !item.isSelected;
}
});
if (item.isSelected) {
arrSelected.push(item);
if (onContactSelected) {
onContactSelected(item);
}
} else {
if (onContactRemove) {
onContactRemove(item);
}
arrSelected.splice(arrSelected.indexOf(item), 1);
}
this.setState({contactList: arrContact, selectedContact: arrSelected});
};
checkExist = item => {
const {onContactRemove} = this.props;
let arrContact = this.state.contactList;
let arrSelected = this.state.selectedContact;
arrContact.map(listItem => {
if (listItem.id === item.id) {
listItem.isSelected = false;
}
});
if (onContactRemove) {
onContactRemove(item);
}
arrSelected.splice(arrSelected.indexOf(item), 1);
this.setState({contactList: arrContact, selectedContact: arrSelected});
};
SearchFilterFunction = text => {
let newArr = [];
this.arrayholder.map(function(item) {
const itemData = item.fullname.toUpperCase();
const textData = text.toUpperCase();
if (itemData.indexOf(textData) > -1) {
newArr.push(item);
}
});
this.setState({
contactList: newArr,
text: text,
});
};
//Render Method
_renderItem = ({item}) => {
const {viewCheckMarkStyle} = this.props;
return (
<TouchableOpacity onPress={() => this.checkContact(item)}>
<View style={styles.viewContactList}>
<Image
source={
item.avatar !== ''
? {uri: item.avatar}
: require('../images/user.png')
}
style={styles.imgContactList}
/>
<View style={styles.nameContainer}>
<Text style={styles.txtContactList}>{item.fullname}</Text>
<Text style={styles.txtPhoneNumber}>{item.phoneNumber}</Text>
</View>
{item.isSelected && (
<Image
source={require('../images/check-mark.png')}
style={[styles.viewCheckMarkStyle, viewCheckMarkStyle]}
/>
)}
</View>
</TouchableOpacity>
);
};
state = {
//We will store selected item in this
selectedItems: [],
};
onSelectedItemsChange = selectedItems => {
this.setState({selectedItems});
//Set Selected Items
};
render() {
const {selectedItems} = this.state;
const {searchBgColor, searchPlaceholder, viewSepratorStyle} = this.props;
return (
<View style={styles.container}>
<MultiSelect
hideTags
items={this.contactList}
uniqueKey="id"
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={this.onSelectedItemsChange}
selectedItems={selectedItems}
selectText="Select Contacts"
searchInputPlaceholderText="Search Contacts..."
onChangeInput={text => console.log(text)}
tagRemoveIconColor="#ff0000"
tagBorderColor="#48d22b"
tagTextColor="#000"
selectedItemTextColor="#48d22b"
selectedItemIconColor="#48d22b"
itemTextColor="#000"
displayKey="name"
searchInputStyle={{color: '#48d22b'}}
submitButtonColor="#48d22b"
submitButtonText="Submit"
/>
<View>
{this.multiSelect &&
this.multiSelect.getSelectedItemsExt(selectedItems)}
</View>
{this.state.isLoading && (
<View style={styles.loading}>
<ActivityIndicator animating={true} size="large" color="gray" />
</View>
)}
</View>
);
}
}
Tab2.propTypes = {
otherContactList: PropTypes.array,
viewCloseStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
]),
viewCheckMarkStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
]),
sepratorStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
]),
viewSepratorStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
]),
searchBgColor: PropTypes.string,
searchPlaceholder: PropTypes.string,
onContactSelected: PropTypes.func,
onContactRemove: PropTypes.func,
};
Tab2.defaultProps = {
otherContactList: [],
viewCloseStyle: {},
viewCheckMarkStyle: {},
sepratorStyle: {},
viewSepratorStyle: {},
searchBgColor: 'rgb(202,201,207)',
searchPlaceholder: 'Search...',
onContactSelected: () => {},
onContactRemove: () => {},
};
export default Tab2;
your multiselect should be given the contacts. Try stripping out anything nonessential from your example
...
render() {
...
return (
...
<MultiSelect
items={this.state.contactList}
...
/>
...
);
}

react native modal not close after setState false

I have set modal visibility to false but it still showing. I cant figure out what causes this issue. this my code at loading.js.
I'm use this component in main what happen when setState false but its just close after close simolator and restart the device
import React,{Component} from 'react';
import PropTypes from 'prop-types'
import {View, Image, Modal, StyleSheet, Text} from "react-native";
export default class Loader extends Component{
render(){
const {animationType,modalVisible}=this.props;
return(
<Modal
animationType={animationType}
transparent={true}
visible={modalVisible}>
<View style={styles.wrapper}>
<View style={styles.loaderContainer}>
<Image
source={require('../img/loading.gif')}
style={styles.loaderImage}/>
</View>
</View>
</Modal>
)
}
}
Loader.propTypes={
animationType:PropTypes.string.isRequired,
modalVisible:PropTypes.bool.isRequired
}
this main class
export default class ForoshRah extends Component {
constructor() {
super();
I18nManager.forceRTL(true);
this.state = {
image: null,
images: null,
loadingVisible:false,
};
this.onValueChange2=this.onValueChange2.bind(this);
this.OnSubmiteData=this.OnSubmiteData.bind(this);
}
onValueChange2(value: string) {
this.setState({
Field: value,
});
}
async OnSubmiteData(){
this.setState({loadingVisible:true})
let token = await AsyncStorage.getItem('token',token);
let response = await
fetch(url,{
method:'POST',
headers:{
'Content-Type':'application/json',
Authorization:'JWT'+" "+token,
}
,body: JSON.stringify({
title,
})
})
let register = await response.json();
this.setState({userID:register.id})
if(response.status===200){
this.UploadImage()
}
}
async UploadImage() {
let token = await AsyncStorage.getItem('token',token);
let response = await fetch(url,{
method:'POST',
headers:{
Authorization:'JWT'+" "+token,
},body: formData
})
let uimage = await response;
console.log('user',this.state.userID);
if(response.status=200){
handleCloseModal = () => {
console.log(this.state.loadingVisible);
this.setState({ loadingVisible: false})
});
};
this.props.navigation.dispatch({ type: 'Navigation/BACK' })
}else {
setTimeout(() => {
this.setState({ loadingVisible: false })
}, 100)
}
setTimeout(() => {
this.setState({ loadingVisible: false })
}, 100)
}
render() {
return (
<KeyboardAwareScrollView >
<View style={{marginBottom:'10%'}}>
<Button block style={{backgroundColor:'#8e25a0'}} onPress={this.OnSubmiteData.bind(this)}>
</Button>
</View>
<Loader
modalVisible={loadingVisible}
animationType="fade"
/>
</KeyboardAwareScrollView>
);
}
}
onsubmitdata setState true and after response going to 200 Setstate set false in code main
You cannot just call state name as you have did. You should do like below.
<Loader
modalVisible={this.state.loadingVisible}
animationType="fade"
/>

React native - Can't dispatch action in component because state gets undefined

In my react native android app, when I try to dispatch an action in BoardsScreen or in the root of the app, the following error pops up:
However, when I remove it, the app doesn't crashes.
BoardsScreen.js
import React from 'react';
import { connect } from 'react-redux';
import { Container, Content, Text, List, Button, Icon, ListItem } from 'native-base';
import { ListView, StatusBar } from 'react-native';
import { ConfirmDialog } from 'react-native-simple-dialogs';
import ActionButton from 'react-native-action-button';
import { removeBoard } from '../actions/configurationActions';
class BoardsScreen extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
boardDeleteDialog: false,
secId: null,
rowId: null,
rowMap: null,
};
}
deleteRow(secId, rowId, rowMap) {
rowMap[`${secId}${rowId}`].props.closeRow();
const newData = [...this.props.boards];
newData.splice(rowId, 1);
this.props.removeBoard(newData);
this.setState({
rowId: null,
secId: null,
rowMap: null,
boardDeleteDialog: false,
});
}
dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
render() {
console.log(this.props.boards);
return (
<Container>
<StatusBar backgroundColor="#00C853" />
<ConfirmDialog
title="Delete board?"
animationType="fade"
visible={this.state.boardDeleteDialog}
positiveButton={{
title: 'Delete',
titleStyle: {
color: '#2ecc71',
},
onPress: () => this.deleteRow(this.state.secId, this.state.rowId, this.state.rowMap),
}}
negativeButton={{
titleStyle: {
color: '#2ecc71',
},
title: 'Cancel',
onPress: () =>
this.setState({
boardDeleteDialog: false,
secId: null,
rowId: null,
rowMap: null,
}),
}}
/>
<Content>
{this.props.boards.length >= 1 ? (
<List
style={{ backgroundColor: '#D9534F' }}
dataSource={this.dataSource.cloneWithRows(this.props.boards)}
renderRow={data => (
<ListItem
style={{ paddingLeft: 14, backgroundColor: 'transparent' }}
button
onPress={() =>
this.props.navigation.navigate('Board', {
board: data.board,
boardName: data.boardName,
})
}
>
<Text>{data.boardName}</Text>
</ListItem>
)}
renderRightHiddenRow={(data, secId, rowId, rowMap) => (
<Button
full
danger
onPress={() =>
this.setState({
boardDeleteDialog: true,
secId,
rowId,
rowMap,
})
}
>
<Icon active name="trash" />
</Button>
)}
disableRightSwipe
rightOpenValue={-75}
/>
) : (
<Text>No boards added.</Text>
)}
</Content>
<ActionButton
buttonColor="#2ecc71"
fixNativeFeedbackRadius
onPress={() => this.props.navigation.navigate('AddBoard')}
/>
</Container>
);
}
}
const mapStateToProps = state => ({
boards: state.configurationReducer.boards,
});
const mapDispatchToProps = dispatch => ({
removeBoard: (board) => {
dispatch(removeBoard(board));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(BoardsScreen);
App.js
import React from 'react';
import { connect } from 'react-redux';
import MainNavigator from './src/config/Router';
import { addBoardToList } from './src/actions/configurationActions';
import { Board } from './src/API';
class App extends React.PureComponent {
componentDidMount() {
Board.getList(true).then(response => this.parseDataFromJSONResponse(response));
}
parseDataFromJSONResponse(response) {
for (let i = 0; i < response.length; i += 1) {
this.props.addBoardToList(response[1]);
}
}
render() {
return <MainNavigator />;
}
}
const mapStateToProps = state => ({
boards: state.configurationReducer.boards,
});
const mapDispatchToProps = dispatch => ({
addBoardToList: (board) => {
dispatch(addBoardToList(board));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
configurationReducer.js
const initialState = {
theme: 1,
obscure: false,
boards: [],
boardsList: [],
};
const configurationReducer = (state = initialState, action) => {
let newState = { ...state };
switch (action.type) {
case 'ADD_BOARD':
newState = {
boards: [...state.boards, action.payload],
};
return newState;
case 'REMOVE_BOARD':
newState = {
boards: action.payload,
};
return newState;
case 'ADD_BOARD_TO_LIST':
newState = {
boardsList: [...state.boardsList, action.payload],
};
return newState;
default:
return state;
}
};
export default configurationReducer;
configurationActions.js
function addBoard(board) {
return {
type: 'ADD_BOARD',
payload: board,
};
}
function removeBoard(board) {
return {
type: 'REMOVE_BOARD',
payload: board,
};
}
function addBoardToList(board) {
return {
type: 'ADD_BOARD_TO_LIST',
payload: board,
};
}
export { addBoard, removeBoard, addBoardToList };
I really don't have a clue what is causing this, maybe it's a bug but I don't know if is react-redux fault or react native itself.
When you remove the board, it looks like in you reducer, you return a strange new state:
case 'REMOVE_BOARD':
newState = {
boards: action.payload,
};
return newState;
Should the boards to be an array always? I think you missed something, for example:
boards: state.boards.filter ((it) => it.id !== action.payload.id),

React native signed APK crash

Signed APK crash after launch, in logCat i got requiring unknown module 'React'
Debug application works fine, but in logCat i got >> Requiring module 'React' by name is only supported for debugging purposes and will BREAK IN PRODUCTION!
React v15.4.1, React native v0.39.2 ?
Sorry for my english
this is my index.android.js
import React from 'react';
import {AppRegistry} from 'react-native';
import myapp from './index_start.js';
AppRegistry.registerComponent('myapp', () => myapp);
and index_start.js
import React, { Component } from "react";
import {
StyleSheet,
AppRegistry,
Text,
Image,
View,
AsyncStorage,
NetInfo,
StatusBar,
Navigator,
Dimensions
} from 'react-native';
// Window dismensions
const { width, height } = Dimensions.get('window');
// Device infos
import DeviceInfo from 'react-native-device-info';
// Native SplashScreen
import SplashScreen from 'react-native-splash-screen';
// Spinner
import Spinner from 'react-native-spinkit';
// Models
import User from './model/UserModel';
// Json data for initial launch
var DB = require('./DB.json');
// Components
import Stage from './components/stage/stage.js'
import Player from './components/player/player.js'
import Settings from './components/settings/settings.js'
import House from './stages/house/house.js'
// LocalStorage key
var USER_KEY = 'user_key';
const routes = [
{name: 'loading'},
{name: 'stage', component: Stage},
{name: 'house', component: House},
{name: 'settings', component: Settings}
];
const _navigator = null;
export default class myapp extends Component {
constructor(props) {
super(props);
this.state = {
isConnected: false,
isLoading: true,
_navigator: null,
stages: null
}
}
componentWillMount() {
// check if connected
this._checkConnexionType();
}
componentDidMount() {
SplashScreen.hide();
this._loadInitialData();
}
componentDidUpdate() {
// console.log(this.state.stages)
if (!this.state.isLoading && this.state.stages !== null) {
_navigator.push({
name: 'stage',
passProps: {
data: this.state.stages
}
})
}
}
/**
* Load localStorage Data
*/
async _loadInitialData() {
// GET User LocalStorage
if (this.state.stages == null) {
var localData;
//AsyncStorage.removeItem(USER_KEY)
AsyncStorage.getItem(USER_KEY).then((data) => {
if (data !== null) {
var localData = JSON.parse(data);
// User.uuid = localData.uuid;
User.setStages(localData.stages)
this.setState({
'stages' : localData.stages
})
} else {
var storage = {};
storage.setUiid = DeviceInfo.getUniqueID();
storage.stages = DB.stages;
AsyncStorage.setItem(USER_KEY, JSON.stringify(storage));
this.setState({
'stages' : DB.stages
})
}
})
}
if (this.state.isConnected) {
// var rStages = this._loadRemoteStages();
// console.log(rStages);
}
// Change state
setTimeout((function() {
this.setState({
'isLoading': false
})
}).bind(this), 1500);
}
/**
* GET stages from remote DB
*/
async _loadRemoteStages() {
await fetch(API_URL)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
/**
* CHECK IF user is connected to Network
* SET bool to state isLoading
*/
_checkConnexionType() {
NetInfo.isConnected.fetch().then(response => {
this.setState({ isConnected: response})
})
}
_renderScene(route, navigator) {
_navigator = navigator;
if (route.name == 'loading') {
return (
<View style={styles.container}>
<StatusBar hidden={true} />
<Image
style={{width: width, height: height}}
source={require('./img/screen.jpg')}
/>
<View style={styles.loading}>
<Text style={styles.loadingText}>CHARGEMENT</Text>
<Spinner type="ThreeBounce" color={'#fff'}/>
</View>
</View>
)
} else if (route.name == 'stage') {
return (
<Stage navigator={_navigator} {...route.passProps}/>
)
} else if (route.name == 'player') {
return (
<House navigator={_navigator} {...route.passProps}}/>
)
} else if (route.name == 'settings') {
return (
<Settings navigator={_navigator} {...route.passProps}/>
)
}
}
render() {
return (
<Navigator
initialRoute={{name: 'loading'}}
configureScene={() => Navigator.SceneConfigs.FloatFromBottomAndroid}
renderScene={this._renderScene.bind(this)}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
loading: {
flex: 1,
position: 'absolute',
bottom: 50,
left: 0,
right: 0,
alignItems: 'center',
},
loadingText:{
flex: 1,
fontFamily: 'CarterOne',
fontSize: 20,
color: '#fff'
}
});

Chai testing on React App returning unexpected result

Hi I ran the following test and the test confirmed that ChannelListItem exists:
import React from 'react';
//import expect from 'expect';
import { expect } from 'chai';
import io from 'socket.io-client';
import sinon from 'sinon';
import { Provider } from 'react-redux';
import configureStore from '../../src/common/store/configureStore';
import { shallow,mount } from 'enzyme';
import Channels from '../../src/common/components/Channels';
import ChannelListItem from '../../src/common/components/ChannelListItem';
import { fakeChannels } from '../fakeData/channelsFake';
import { fakeMessages } from '../fakeData/messagesFake';
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
const socket = io('', { path: '/api/chat' });
describe('Channels', () => {
const changeActiveChannel = sinon.spy()
const dispatch = sinon.spy(store, 'dispatch')
let Component;
beforeEach(() => {
Component =
shallow(<Provider store={store}>
<Channels
socket = {socket}
onClick = {changeActiveChannel}
channels = {fakeChannels}
messages = {fakeMessages}
dispatch = {dispatch}
/>
</Provider>);
});
it('should render', () => {
expect(Component).to.be.ok;
});
it('should have a ChannelListItem', () => {
const channelListItem = Component.find('ChannelListItem')
expect(channelListItem).to.exist;
However, when I ran the following test, I got channelListItem.length equal 0
expect(channelListItem.length).to.equal(3);
Any ideas what could be wrong? I clearly have a channelListItem inside my Channel component:
return (
<ChannelListItem style={{paddingLeft: '0.8em', background: '#2E6DA4', height: '0.7em'}} channel={'aa'} key={'1'} onClick={::this.handleChangeChannel} />
);
Code for Channels:
import React, { Component, PropTypes } from 'react';
import ChannelListItem from './ChannelListItem';
import ChannelListModalItem from './ChannelListModalItem';
import { Modal, Glyphicon, Input, Button } from 'react-bootstrap';
import * as actions from '../actions/actions';
import uuid from 'node-uuid';
import { createChannel } from '../reducers/channels';
export default class Channels extends Component {
static propTypes = {
channels: PropTypes.array.isRequired,
onClick: PropTypes.func.isRequired,
messages: PropTypes.array.isRequired,
dispatch: PropTypes.func.isRequired
};
constructor(props, context) {
super(props, context);
this.state = {
addChannelModal: false,
channelName: '',
moreChannelsModal: false
};
}
handleChangeChannel(channel) {
if(this.state.moreChannelsModal) {
this.closeMoreChannelsModal();
}
this.props.onClick(channel);
}
openAddChannelModal(event) {
//event.preventDefault();
this.setState({addChannelModal: true});
}
closeAddChannelModal(event) {
event.preventDefault();
this.setState({addChannelModal: false});
}
handleModalChange(event) {
this.setState({channelName: event.target.value});
}
handleModalSubmit(event) {
const { channels, dispatch, socket } = this.props;
event.preventDefault();
if (this.state.channelName.length < 1) {
this.refs.channelName.getInputDOMNode().focus();
}
if (this.state.channelName.length > 0 && channels.filter(channel => {
return channel.name === this.state.channelName.trim();
}).length < 1) {
const newChannel = {
name: this.state.channelName.trim(),
id: `${Date.now()}${uuid.v4()}`,
private: false
};
dispatch(createChannel(newChannel));
this.handleChangeChannel(newChannel);
socket.emit('new channel', newChannel);
this.setState({channelName: ''});
this.closeAddChannelModal(event);
}
}
validateChannelName() {
const { channels } = this.props;
if (channels.filter(channel => {
return channel.name === this.state.channelName.trim();
}).length > 0) {
return 'error';
}
return 'success';
}
openMoreChannelsModal(event) {
event.preventDefault();
this.setState({moreChannelsModal: true});
}
closeMoreChannelsModal(event) {
//event.preventDefault();
this.setState({moreChannelsModal: false});
}
createChannelWithinModal() {
this.closeMoreChannelsModal();
this.openAddChannelModal();
}
render() {
const { channels, messages } = this.props;
const filteredChannels = channels.slice(0, 8);
const moreChannelsBoolean = channels.length > 8;
const restOfTheChannels = channels.slice(8);
const newChannelModal = (
<div>
<Modal key={1} show={this.state.addChannelModal} onHide={::this.closeAddChannelModal}>
<Modal.Header closeButton>
<Modal.Title>Add New Channel</Modal.Title>
</Modal.Header>
<Modal.Body>
<form onSubmit={::this.handleModalSubmit} >
<Input
ref="channelName"
type="text"
help={this.validateChannelName() === 'error' && 'A channel with that name already exists!'}
bsStyle={this.validateChannelName()}
hasFeedback
name="channelName"
autoFocus="true"
placeholder="Enter the channel name"
value={this.state.channelName}
onChange={::this.handleModalChange}
/>
</form>
</Modal.Body>
<Modal.Footer>
<Button onClick={::this.closeAddChannelModal}>Cancel</Button>
<Button disabled={this.validateChannelName() === 'error' && 'true'} onClick={::this.handleModalSubmit} type="submit">
Create Channel
</Button>
</Modal.Footer>
</Modal>
</div>
);
const moreChannelsModal = (
<div style={{background: 'grey'}}>
<Modal key={2} show={this.state.moreChannelsModal} onHide={::this.closeMoreChannelsModal}>
<Modal.Header closeButton >
<Modal.Title>More Channels</Modal.Title>
<a onClick={::this.createChannelWithinModal} style={{'cursor': 'pointer', 'color': '#85BBE9'}}>
Create a channel
</a>
</Modal.Header>
<Modal.Body>
<ul style={{height: 'auto', margin: '0', overflowY: 'auto', padding: '0'}}>
{restOfTheChannels.map(channel =>
<ChannelListModalItem channel={channel} key={channel.id} onClick={::this.handleChangeChannel} />
)}
</ul>
</Modal.Body>
<Modal.Footer>
<button onClick={::this.closeMoreChannelsModal}>Cancel</button>
</Modal.Footer>
</Modal>
</div>
);
return (
<section>
<div>
<span style={{paddingLeft: '0.8em', fontSize: '1.5em'}}>
Channels
<button onClick={::this.openAddChannelModal} style={{fontSize: '0.8em', 'background': 'Transparent', marginLeft: '2.8em', 'backgroundRepeat': 'noRepeat', 'border': 'none', 'cursor': 'pointer', 'overflow': 'hidden', 'outline': 'none'}}>
<Glyphicon glyph="plus" />
</button>
</span>
</div>
{newChannelModal}
<div>
<ul style={{display: 'flex', flexDirection: 'column', listStyle: 'none', margin: '0', overflowY: 'auto', padding: '0'}}>
{filteredChannels.map(channel =>
<ChannelListItem style={{paddingLeft: '0.8em', background: '#2E6DA4', height: '0.7em'}} messageCount={messages.filter(msg => {
return msg.channelID === channel.name;
}).length} channel={channel} key={channel.id} onClick={::this.handleChangeChannel} />
)}
</ul>
{moreChannelsBoolean && <a onClick={::this.openMoreChannelsModal} style={{'cursor': 'pointer', 'color': '#85BBE9'}}> + {channels.length - 8} more...</a>}
{moreChannelsModal}
</div>
</section>
);
}
}