React container with render logic? - reactjs

I have a container, which renders 3 components:
1. list of items
2. new item modal
3. edit item modal
In order to control the whole container functions, I need to call the list of items with column list. Is it ok that all will be inside the container?
Is it ok to render modal within the container? (The modal contains the 2 and 3 components)
class Items extends React.Component {
constructor(props) {
super(props)
this.state = {
modal: false
}
this.columns = [
...
]
this.closeModal = this.closeModal.bind(this)
}
openModal(type, item) {
this.setState({
modal: {
type,
item: item && item.toJS()
}
})
}
closeModal() {
this.setState({modal: false})
}
renderModal() {
const {item, type} = this.state.modal;
return (
<Modal onClose={this.closeModal}>
{type == modalTypes.NEW_ITEM &&
<ItemForm onCancel={this.closeModal}
onSubmit={...}/>}
{type == modalTypes.REMOVE_ITEM &&
<ConfirmationDialog text="Are you sure you want to remove?"
onSubmit={...} onCancel={this.closeModal}/>}
{type == modalTypes.EDIT_ITEM &&
<ItemForm onCancel={this.closeModal}
onSubmit={...}/>}
</Modal>
)
}
render() {
const {visibleItems, display_type} = this.props;
return (
<div>
<div className="_header_container">
<Header title="Items"/>
<div className="actions">
<Search />
<DisplayToggle />
<Button size="sm" color="primary"
onClick={() => ...}
</div>
</div>
{display_type == displayType.GRID &&
<Grid items={visibleItems} columns={this.columns}/>}
{display_type == displayType.TILE &&
<TileView items={visibleItems} titleKey="name" linkKey="url"/>}
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
remove: (item) => dispatch(remove(item)),
edit: (item, ...) => dispatch(edit(item, ...)),
create: (name, val) => dispatch(create(name, url)),
}
}
const mapStateToProps = (state) => {
return {
visibleItems: filterItems(state.items, state.search),
display_type: state.display_type
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Items)
Thanks

Related

React function - is not defined no-undef

I get the following error when trying to compile my app 'handleProgress' is not defined no-undef.
I'm having trouble tracking down why handleProgress is not defined.
Here is the main react component
class App extends Component {
constructor(props) {
super(props);
this.state = {
progressValue: 0,
};
this.handleProgress = this.handleProgress.bind(this);
}
render() {
const { questions } = this.props;
const { progressValue } = this.state;
const groupByList = groupBy(questions.questions, 'type');
const objectToArray = Object.entries(groupByList);
handleProgress = () => {
console.log('hello');
};
return (
<>
<Progress value={progressValue} />
<div>
<ul>
{questionListItem && questionListItem.length > 0 ?
(
<Wizard
onChange={this.handleProgress}
initialValues={{ employed: true }}
onSubmit={() => {
window.alert('Hello');
}}
>
{questionListItem}
</Wizard>
) : null
}
</ul>
</div>
</>
);
}
}
Your render method is wrong it should not contain the handlePress inside:
You are calling handlePress on this so you should keep it in the class.
class App extends Component {
constructor(props) {
super(props);
this.state = {
progressValue: 0,
};
this.handleProgress = this.handleProgress.bind(this);
}
handleProgress = () => {
console.log('hello');
};
render() {
const { questions } = this.props;
const { progressValue } = this.state;
const groupByList = groupBy(questions.questions, 'type');
const objectToArray = Object.entries(groupByList);
return (
<>
<Progress value={progressValue} />
<div>
<ul>
{questionListItem && questionListItem.length > 0 ?
(
<Wizard
onChange={this.handleProgress}
initialValues={{ employed: true }}
onSubmit={() => {
window.alert('Hello');
}}
>
{questionListItem}
</Wizard>
) : null
}
</ul>
</div>
</>
);
}
}
If you are using handleProgress inside render you have to define it follows.
const handleProgress = () => {
console.log('hello');
};
if it is outside render and inside component then use as follows:
handleProgress = () => {
console.log('hello');
};
If you are using arrow function no need to bind the function in constructor it will automatically bind this scope.
handleProgress should not be in the render function, Please keep functions in you component itself, also if you are using ES6 arrow function syntax, you no need to bind it on your constructor.
Please refer the below code block.
class App extends Component {
constructor(props) {
super(props);
this.state = {
progressValue: 0,
};
// no need to use bind in the constructor while using ES6 arrow function.
// this.handleProgress = this.handleProgress.bind(this);
}
// move ES6 arrow function here.
handleProgress = () => {
console.log('hello');
};
render() {
const { questions } = this.props;
const { progressValue } = this.state;
const groupByList = groupBy(questions.questions, 'type');
const objectToArray = Object.entries(groupByList);
return (
<>
<Progress value={progressValue} />
<div>
<ul>
{questionListItem && questionListItem.length > 0 ?
(
<Wizard
onChange={this.handleProgress}
initialValues={{ employed: true }}
onSubmit={() => {
window.alert('Hello');
}}
>
{questionListItem}
</Wizard>
) : null
}
</ul>
</div>
</>
);
}
}
Try this one, I have check it on react version 16.8.6
We don't need to bind in new version using arrow head functions. Here is the full implementation of binding argument method and non argument method.
import React, { Component } from "react";
class Counter extends Component {
state = {
count: 0
};
constructor() {
super();
}
render() {
return (
<div>
<button onClick={this.updateCounter}>NoArgCounter</button>
<button onClick={() => this.updateCounterByArg(this.state.count)}>ArgCounter</button>
<span>{this.state.count}</span>
</div>
);
}
updateCounter = () => {
let { count } = this.state;
this.setState({ count: ++count });
};
updateCounterByArg = counter => {
this.setState({ count: ++counter });
};
}
export default Counter;

How to toggle dynamically generated dropdowns using the .map functions index?

I have a array that for every item in the array a drop down list is dynamically generated. Right now each drop down list share the same toggle boolean so they all open and close and the same time, how can I make this work individually?
I map each object to a index here and then start creating dropdowns:
{Object.keys(props.totalWorkload.options).map((item, i) => (
<WorkloadOptions
key={i}
cnt={i}
appendChoiceList={props.appendChoiceList}
modalDropDown={props.modalDropDown}
toggleDropDown={props.toggleDropDown}
totalWorkloadOptions={props.totalWorkload.options[item]}
/>
))}
When the Drop Down options component is created I pass the index to a function:
<div>
<Dropdown isOpen={props.modalDropDown} toggle={props.toggleDropDown.bind(props.cnt)}>
<DropdownToggle caret>{props.totalWorkloadOptions.optionTitle}</DropdownToggle>
<DropdownMenu>
{props.totalWorkloadOptions.options.map(op => (
// tslint:disable-next-line:no-invalid-this
// tslint:disable-next-line:jsx-no-lambda
<DropdownItem key={op} onClick= {() => props.appendChoiceList(props.totalWorkloadOptions.optionTitle, op)}>
{op}
</DropdownItem>
))}
</DropdownMenu>
<strong> {props.totalWorkloadOptions.optionDescription} </strong>
</Dropdown>
<br />
</div>
The it will arrrive at the following functuion and console log the index and then set the appropriate toggle value in an array to true/false:
toggleDropDown = (index: any) => {
console.log('triggered!:' + index);
let clicked = this.state.modalDropDownClicked;
// tslint:disable-next-line:no-conditional-assignment
if (clicked[index]=!clicked[index]){
this.setState({ modalDropDownClicked: !this.state.modalDropDown[index] });
}
};
I can recommend the following pattern to toggle dynamically created elements:
// Item.js
class Item extends React.Component {
handleClick = () => {
const { id, onClick } = this.props;
onClick(id);
}
render() {
const { isOpen } = this.props;
return (
<li><button onClick={this.handleClick}>{isOpen ? 'open' : 'closed'}</button></li>
)
}
}
// App.js
class App extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {
const { items } = nextProps;
if (items !== prevState.prevPropsItems) {
return { items, prevPropsItems: items };
}
return null;
}
state = {
prevPropsItems: [],
items: []
}
toggleItem = id => this.setState(prevState => {
const items = prevState.items.map(item => {
if (item.id === id) {
return { ...item, isOpen: !item.isOpen }
} else {
return item;
}
});
return { items }
})
render(){
const { items } = this.state;
return (<ul>
{items.map(item => <Item key={item.id} id={item.id} onClick={this.toggleItem} isOpen={item.isOpen} />)}
</ul>);
}
}
// AppContainer.js
const itemsFromRedux = [
{ id: '1', isOpen: false },
{ id: '2', isOpen: false },
{ id: '3', isOpen: false },
]
ReactDOM.render(<App items={itemsFromRedux} />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.development.js"></script>
<div id="root"></div>

Why handler calls render method 3 times?

I'm working with Semantic-ui and have such component with list of
items. Every item has group of checkboxes:
import React, { Component } from 'react'
import { Divider,Label,List,Checkbox,Header } from 'semantic-ui-react'
export default class Menu extends Component {
constructor(props) {
super(props);
this.state = {
checkboxes: []
}
}
render() {
let { tags } = this.props;
return (
<div className="ui segment basic" >
{typeof tags === "undefined" ?
<div>Select partner and process</div>
:
this.getTagListItems(tags)
}
</div>
)
}
getTagListItems = tagsData => {
let tags = [];
for(let i=0; i<tagsData.length; i++){
if ( tagsData[i].children.length !==0 ) {
tags.push(
<div className="container" key = { i }>
<Header as="h3">{ tagsData[i].name }</Header>
<Divider/>
<List>
{this.getTagCheckboxes(tagsData[i].children)}
</List>
</div>
);
}
}
return tags;
};
getTagCheckboxes = checkboxData => {
let checkboxes = [];
for(let i=0; i<checkboxData.length; i++) {
checkboxes.push(
<List.Item key = { checkboxData[i].id }>
<Checkbox label = { checkboxData[i].name }
id = { checkboxData[i].id }
onClick = { this.setCheckbox }
// checked = { this.state.data.id === checkboxData[i].id }
/>
<List.Content floated="right" >
<Label>
0
</Label>
</List.Content>
</List.Item>
);
}
return checkboxes;
};
setCheckbox = (e, itemData) => {
let { checkboxes } = this.state;
console.log('ITEMM!!!', itemData)
}
}
How it can be seen on every checkbox I set onClick, which calls setCheckbox. When I check just 1 checkbox, it calls setCheckbox 3 times and I get in console console.log for 3 times. What's wrong, how can I correct it in order setCheckbox works only 1 time per 1 check?
Problem was in onClick. I changed it to onChange() and now it works

Showing two different components based on return value in react js

I have search function where on entering text it returns the object from an array(json data) and based on the condition (whether it as an object or not) I need to show two different components ie. the list with matched fields and "No matched results found" component.
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
searchTextData: '',
isSearchText: false,
isSearchOpen: false,
placeholderText:'Search Content',
filteredMockData: [],
dataArray: []
};
}
handleSearchChange = (event, newVal) => {
this.setState({ searchTextData: newVal })
if (newVal == '') {
this.setState({ clearsearch: true });
this.setState({
filteredMockData: []
});
this.props.onDisplayCloseIcon(true);
} else {
this.props.onDisplayCloseIcon(false);
searchData.searchResults.forEach((item, index, array) => {
this.state.dataArray.push(item);
});
this.setState({ filteredMockData: this.state.dataArray });
}
}
clearInput = () => {
this.setState({ searchTextData: '' })
}
isSearchText = () => {
this.setState({ isSearchText: !this.state.isSearchText });
}
onSearchClick = () => {
this.setState({ isSearchOpen: !this.state.isSearchOpen });
this.setState({ searchTextData: '' });
this.props.onDisplayCloseIcon(true);
}
renderSearchData = () => {
const SearchDatasRender = this.state.dataArray.map((key) => {
const SearchDataRender = key.matchedFields.pagetitle;
return (<ResultComponent results={ SearchDataRender } /> );
})
return SearchDatasRender;
}
renderUndefined = () => {
return ( <div className = "search_no_results" >
<p> No Recent Searches found. </p>
<p> You can search by word or phrase, glossary term, chapter or section.</p>
</div>
);
}
render() {
return ( <span>
<SearchIcon searchClick = { this.onSearchClick } />
{this.state.isSearchOpen &&
<div className = 'SearchinputBar' >
<input
placeholder={this.state.placeholderText}
className= 'SearchInputContent'
value = { this.state.searchTextData}
onChange = { this.handleSearchChange }
/>
</div>
}
{this.state.searchTextData !== '' && this.state.isSearchOpen &&
<span className='clearText'>
<ClearIcon className='clearIcon' clearClick = { this.clearInput }/>
</span>
}
{this.state.searchTextData !== '' && this.state.isSearchOpen &&
<div className="SearchContainerWrapper">
<div className = "arrow-up"> </div>
<div className = 'search_result_Container' >
<div className = "search_results_title" > <span> Chapters </span><hr></hr> </div>
<div className="search_show_text" >
<ul className ="SearchScrollbar">
{this.state.filteredMockData.length ? this.renderSearchData() : this.renderUndefined() }
</ul>
</div>
</div>
</div>}
</span>
);
}
}
Search.propTypes = {
intl: intlShape.isRequired,
onSearchClick: PropTypes.func,
isSearchBarOpen: PropTypes.func,
clearInput: PropTypes.func,
isSearchText: PropTypes.func
};
export default injectIntl(Search);
Search is my parent component and based on the matched values I need to show a resultComponent like
class ResultComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render(){
console.log(this.props.renderSearchData(),'Helloooo')
return(<p>{this.props.renderSearchData()}</p>)
}
}
ResultComponent.propTypes = {
results: PropTypes.string.isRequired
};
I'm getting an error "renderSearchData is not an function".I'm new to react and Hope someone can help.
The only prop passed to ResultComponent component is results
So in ResultComponent Component Replace
this.props.renderSearchData()
With
this.props.results

redux-form always returns same values for Multiselect react-widget

I am trying to use redux-form with react-widget Multiselect this example:
var Multiselect = ReactWidgets.Multiselect
, people = listOfPeople();
var Example = React.createClass({
getInitialState() {
return { value: people.slice(0,2) };
},
_create(name){
var tag = { name, id: people.length + 1 }
var value = this.state.value.concat(tag)
// add new tag to the data list
people.push(tag)
//add new tag to the list of values
this.setState({ value })
},
render(){
// create a tag object
return (
<Multiselect data={people}
value={this.state.value}
textField="name"
onCreate={this._create}
onChange={value => this.setState({ value })}/>
)
}
});
ReactDOM.render(<Example/>, mountNode);
Below is a code snippet for a parent component which makes usage of redux-form (EditVideo component) component (please look at the comments in onSubmit method):
class VideoEdit extends React.Component {
constructor(props) {
super(props);
}
onSubmit = (values) => {
console.log(values.categories) // always returns initialValues for categories, new values not adding
}
render() {
const { loading, videoEdit, categories } = this.props;
if (loading) {
return (
<div>{ /* loading... */}</div>
);
} else {
return (
<div>
<h2>Edit: {videoEdit.title}</h2>
<EditVideo
onSubmit={this.onSubmit}
initialValues={videoEdit}
categories={categories}
/>
</div>
);
}
}
}
And here is a code snippet of redux-form component with react-widget Multiselect component:
class CategoryWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.defValue,
extData: this.props.data
}
this._create = this._create.bind(this);
}
_create(name) {
var tag = { name, id: this.state.extData.length + 100 + 1 }
var value = this.state.value.concat(tag)
var extData = this.state.extData.concat(tag)
this.setState({
extData,
value
})
}
render() {
return (
<Multiselect
{...this.props.input}
data={this.state.extData}
onBlur={() => this.props.input.onBlur()}
value={this.state.value || []}
valueField="id"
textField="name"
onCreate={this._create}
onChange={value => this.setState({ value })}
/>
)
}
}
const EditVideoForm = (props) => {
const { handleSubmit, submitting, onSubmit, categories, initialValues, defBook } = props;
return (
<Form name="ytvideo" onSubmit={handleSubmit(onSubmit)}>
<div>
<Field
name="categories"
component={CategoryWidget}
data={categories}
defValue={initialValues.categories}
/>
</div>
<br />
<Button color="primary" type="submit" disabled={submitting}>
Submit
</Button>
</Form>
);
};
export default reduxForm({
form: 'videoEdit',
enableReinitialize: true
})(EditVideoForm);
The Multiselect widget works as expected, yet the form on submit always returns the same initial values for categories.
I believe the problem lays in the fact that CategoryWidget is a class base component? If so, what is a way to make it work?
Here is what I have done for my Multiselect at the end:
class CategoryWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.defValue,
extData: this.props.data
}
this._create = this._create.bind(this);
}
_create(name) {
var tag = { name, id: this.state.extData.length + 100 + 1 }
var value = this.state.value.concat(tag)
var extData = this.state.extData.concat(tag)
this.setState({
extData,
value
})
}
componentDidUpdate() {
let { onChange } = this.props.input
onChange(this.state.value)
}
handleOnChange(value) {
this.setState({ value })
}
render() {
const input = this.props.input
return (
<Multiselect
{...input}
data={this.state.extData}
onBlur={() => input.onBlur()}
value={this.state.value || []}
valueField="id"
textField="name"
onCreate={this._create}
onChange={value => this.handleOnChange(value)}
/>
)
}
}

Resources