ReactJs data inside loop empty - javascript

<div className="col-md-12">
<div className="row">
{shopeeship.map(function (key,value) {
if(key.enabled){
console.log("yes");
<div className="col-md-6">
<div className="form-group">
<span className="mr-4 pr-4">
<IntlMessages id="shopee.poswm" />
</span>
<label className="pull-right" title="">
<Switch/>
</label>
</div>
</div>
}})}
</div>
</div>
I have some data and want to loop through it to render some UI. In the above code I tried to loop the data and I checked that if the key enabled then to echo the html value. It successfully prints yes in console log but the html does not render as expected. Anyone has faced such an issue before? Please help.

It's because you forgot to return your html from loop
Do this
<div className="col-md-12">
<div className="row">
{shopeeship.map(function (key,value) {
if(key.enabled){
console.log("yes");
return(
<div className="col-md-6">
<div className="form-group">
<span className="mr-4 pr-4">
<IntlMessages id="shopee.poswm" />
</span>
<label className="pull-right" title="">
<Switch/>
</label>
</div>
</div>
)
}})}
</div>
</div>

You are not returning from map, you can use arrow function instead for implicit return as
<div className="col-md-12">
<div className="row">
{shopeeship.map((key,value) => key.enabled &&
(<div className="col-md-6">
<div className="form-group">
<span className="mr-4 pr-4">
<IntlMessages id="shopee.poswm" />
</span>
<label className="pull-right" title="">
<Switch/>
</label>
</div>
</div>)
)}
</div>
</div>
Hope it helps

you need to return the html part, map creates a new array and expects a return value else your array will be filled with null values, hence you would need to return the said html part.

Try this simplified solution using ternary condition and arrow function.
<div className="col-md-12">
<div className="row">
{shopeeship.map((key,value)=> key.enabled ?
<div className="col-md-6" key={value}>
<div className="form-group">
<span className="mr-4 pr-4">
<IntlMessages id="shopee.poswm" />
</span>
<label className="pull-right" title="">
<Switch/>
</label>
</div>
</div>
:null)}
</div>
</div>

Related

Why can't my React Component find an element?

I have a Component that causes an error, "TypeError: Cannot read property 'value' of null". It's nested inside of another component, and makes that component not load.
This is the code:
const NewItem = (props) => {
const qty = "QuantityBox" + props.identifier.toString();
const prc = "PriceBox" + props.identifier.toString();
return(
<div className="NewItem">
<div className="ItemNameInput">
<p className="InputLabel">Item Name</p>
<input className="inputFull" type="text" />
</div>
<div className="QuantityAndPrice">
<div className="QuantityInput">
<p className="InputLabel">Qty</p>
<input className="inputEighth" value="1" id={qty} type="text" />
</div>
<div className="PriceInput">
<p className="InputLabel">Price</p>
<input className="inputFourth" value="0" id={prc} type="text" />
</div>
<div className="TotalOutput">
<p className="InputLabel">Total</p>
<h4 className="TotalAmount">{(document.getElementById(qty).value * document.getElementById(prc).value).toFixed(2)}</h4>
</div>
<img src={TrashCan} alt="Delete" />
</div>
</div>
)
}
Right in the "TotalAmount" h4, is where the problem arises. If I remove that part, it loads up just fine. Judging from the error, it can't find the elements I'm specifying, but I don't understand why. I don't know if it has anything to do with the parent component, but I'll put it here just in case:
class NewInvoice extends Component {
constructor(props) {
super(props)
this.state = {
numberOfItems: [0]
};
}
createItem = () => {
this.setState(prevState => ({numberOfItems: [...prevState.numberOfItems, (this.state.numberOfItems.length - 1)]}));
}
render() {
return(
<div className="NewInvoice">
<button onClick={() => this.props.goBackInvoiceList()} className="goBack">Go back</button>
<h1>New Invoice</h1>
<form>
<p className="FormAreaLabel">Bill From</p>
<div className="BillFrom">
<div className="StreetAddressInput">
<p className="InputLabel">Street Address</p>
<input className="inputFull" type="text" />
</div>
<div className="HalfInput">
<div className="CityInput">
<p className="InputLabel">City</p>
<input className="inputHalf" type="text" />
</div>
<div className="PostCodeInput">
<p className="InputLabel">Post Code</p>
<input className="inputHalf" type="text" />
</div>
</div>
<div className="NewCountryInput">
<p className="InputLabel">Country</p>
<input className="inputFull" type="text" />
</div>
</div>
<div className="BillTo">
<div className="ClientNameInput">
<p className="InputLabel">Client's Name</p>
<input className="inputFull" type="text" />
</div>
<div className="ClientEmailInput">
<p className="InputLabel">Client's Email</p>
<input className="inputFull" type="text" />
</div>
<div className="ClientStreetAddressInput">
<p className="InputLabel">Street Address</p>
<input className="inputFull" type="text" />
</div>
<div className="HalfInput">
<div className="ClientCityInput">
<p className="InputLabel">City</p>
<input className="inputHalf" type="text" />
</div>
<div className="ClientPostCodeInput">
<p className="InputLabel">Post Code</p>
<input className="inputHalf" type="text" />
</div>
</div>
<div className="ClientCountryInput">
<p className="InputLabel">Country</p>
<input className="inputFull" type="text" />
</div>
</div>
<div className="OtherInfo">
<div className="InvoiceDateInput">
<p className="InputLabel">Invoice Date</p>
<input className="inputFull" type="text" />
</div>
<div className="PaymentTermsInput">
<p className="InputLabel">Payment Terms</p>
<input className="inputFull" type="text" />
</div>
<div className="ProjectDescriptionInput">
<p className="InputLabel">Project Description</p>
<input className="inputFull" type="text" />
</div>
</div>
<h3 className="ItemListTitle">Item List</h3>
<div className="ItemList">
{this.state.numberOfItems.map((index) =>
<NewItem key={index} identifier={index} />
)}
<button onClick={() => this.createItem()} className="AddNewItem">+ Add New Item</button>
</div>
</form>
<div className="NewInvoiceEndButtons">
<button className="Discard">Discard</button>
<button className="SaveAsDraft">Save As Draft</button>
<button className="SaveAndSend">Save And Send</button>
</div>
</div>
)
}
}
This is happening because in the h4 line that you specified, you are trying to retrieve a DOM node with the id "QuantityBox" + props.identifier.toString(). Your code is unable to retrieve a DOM element with a matching id, causing document.getElementById(qty) to return null. null doesn't have any properties, so document.getElementById(qty).value is throwing an error specifiying that it cant access property value of null.
Also, if you want to manipulate DOM elements directly, the React way is to use React Refs. You should be able to achieve your desired result with that.
Read more on Refs here: https://reactjs.org/docs/refs-and-the-dom.html

How to manage visibility of elements in a stepped form

I have a form with steps.
I want other elements to appear after user passes one step.
There should be only one step visible at a time.
I tried for to use a boolean state variable without any luck. All steps appear after passing one.
return (
<UserConsumer>
{value => {
//const {dispatch} = value;
return (
<div>
<Animation pose={visible ? 'visible' : 'hidden'}>
<div className="card col-md-12 mb-4">
<div className="card-body">
<form onSubmit={this.changeVisibility}>
<div className="form-group">
<Text text="Adınız ve Soyadınız" />
</div>
<div className="form-group">
<Input ph="Ad ve Soyad" />
</div>
<Button clickText="İleri" />
</form>
</div>
</div>
</Animation>
<Animation pose={!visible ? 'visible' : 'hidden'}>
{queue.push(
<div className="card col-md-12 mb-4">
<div className="card-body">
<form onSubmit={this.changeVisibility}>
<div className="form-group">
<Text text="E-mail adresiniz" />
</div>
<div className="form-group">
<Input ph="E-mail" />
</div>
<Button clickText="İleri" />
</form>
</div>
</div>,
)}
</Animation>
</div>
)
}}
</UserConsumer>
)
I'm answering this based on your comment that it hides the first one but doesn't display the second one is because you are calling the push which will return the length of new array. So instead of elements from second Animation component it will display a number, fix:
return (
<UserConsumer>
{value => {
//const {dispatch} = value;
return (
<div>
<Animation pose={visible ? 'visible' : 'hidden'}>
<div className="card col-md-12 mb-4">
<div className="card-body">
<form onSubmit={this.changeVisibility}>
<div className="form-group">
<Text text="Adınız ve Soyadınız" />
</div>
<div className="form-group">
<Input ph="Ad ve Soyad" />
</div>
<Button clickText="İleri" />
</form>
</div>
</div>
</Animation>
<Animation pose={!visible ? 'visible' : 'hidden'}>
<div className="card col-md-12 mb-4">
<div className="card-body">
<form onSubmit={this.changeVisibility}>
<div className="form-group">
<Text text="E-mail adresiniz" />
</div>
<div className="form-group">
<Input ph="E-mail" />
</div>
<Button clickText="İleri" />
</form>
</div>
</div>
</Animation>
</div>
)
}}
</UserConsumer>
)

React ReduxForm img upload and validation

I'm trying to create an img uploader inside my ReduxForm that will only accept imgs that are .png and no larger than 210x210 and 2mb. Also, the design says to swap the placeholder img with the uploaded file which I'm also struggling with. Here's my code:
renderProfileImgUpload(field) {
const { meta: { touched, error }, label, name, accept, type } = field;
return (
<div>
<div className="login__fieldError">
<small>{touched ? error : ''}</small>
</div>
<label htmlFor="img-upload">
<img src="imgs/profile-select.png" className="img-responsive" alt="" />
</label>
<input type={type} name={name} accept={accept} id="img-upload" />
</div>
)
}
render() {
const { handleSubmit, showNextRegistration, showPreviousRegistration } = this.props;
return (
<div className="widgetFull--white">
<div className="align-middle row registration--fullHeight">
<div className="columns small-3">
<img
src="imgs/account-arrow-left.png"
alt="menu"
className="img-responsive"
onClick={showPreviousRegistration}
/>
</div>
<div className="columns small-6">
<h2 className="registration__header">Edit account</h2>
</div>
<div className="columns small-3">
<h3 className="registration__index">2 of 2</h3>
</div>
<form onSubmit={ handleSubmit(this.onSubmit.bind(this)) }>
<div className="columns small-3">
<Field label="Profile Image" type="file" name="image" accept="image/.png" component={this.renderProfileImgUpload} />
</div>
<div className="columns small-6">
<Field label="Username" type="screenname" name="screenname" component={this.renderUsernameField} />
</div>
<div className="columns small-6">
<Field label="First Name" type="firstName" name="firstName" component={this.renderFirstNameField} />
</div>
<div className="columns small-6">
<Field label="Last Name" type="lastName" name="lastName" component={this.renderLastNameField} />
</div>
<div className="columns small-12">
<button className="button expanded registration__btn" type="button">Next</button>
</div>
</form>
</div>
</div>
)
}
Currently I'm unsure whether it would be better to try and do the validation when uploading the img, or inside the handle submit function. Thanks for your help!

Displaying elements in three arrays for React

So I am trying to display the contents of three arrays in React in this fashion:
array[one,two]
array2[1,2]
array3[hi, bye]
what I want:
one
1
hi
two
2
bye
But I am ending up with
one
two
1
2
hi
bye
Here is the code and I am usnig paint info to map through and display. I tried nesting the ul's and the li's but not seeming to work... any advice would be greatly appreciated.
this.state = {
paintBrand: ['Sherwin-Williams'],
paintColor: ['Blue'],
paintSheen: ['Satin']
};
this.handleSubmit = this.handleSubmit.bind(this);
//Brads cool
}
handleSubmit(e) {
e.preventDefault();
var updateBrand = this.state.paintBrand;
updateBrand.push(this.refs.brand.value);
var updateColor = this.state.paintColor;
updateColor.push(this.refs.color.value);
var updateSheen = this.state.paintSheen;
updateSheen.push(this.refs.sheen.value);
this.setState({
paintBrand: updateBrand,
paintColor: updateColor,
paintSheen: updateSheen
});
}
render() {
var paintBrandArr = this.state.paintBrand;
paintBrandArr = paintBrandArr.map(brand =>
<li key={brand}>
{brand}
</li>
);
var paintColorArr = this.state.paintColor;
paintColorArr = paintColorArr.map(paint =>
<li key={paint}>
{paint}
</li>
);
var paintSheenArr = this.state.paintSheen;
paintSheenArr = paintSheenArr.map(sheen =>
<li key={sheen}>
{sheen}
</li>
);
return (
<div>
<form className="form" onSubmit={this.handleSubmit}>
<div className="row">
<div className="col-xs-4" />
<div className="col-xs-4">
<label htmlFor="brand">Paint Brand</label>
<div className="field">
<input
type="text"
name="brand"
className="form-control"
placeholder="Brand/Company"
ref="brand"
value={this.props.value}
onChange={this.props.onChange}
/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-4" />
<div className="col-xs-4">
<label htmlFor="color">Color</label>
<div className="field">
<input
type="text"
name="brand"
className="form-control"
placeholder="Color"
ref="color"
value={this.props.value}
onChange={this.props.onChange}
/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-4" />
<div className="col-xs-4">
<label htmlFor="brand">Sheen</label>
<div className="field">
<input
type="text"
name="brand"
className="form-control"
placeholder="Sheen"
ref="sheen"
value={this.props.value}
onChange={this.props.onChange}
/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-12"> </div>
<input
className="btn btn-primary btn-lg"
type="submit"
value="Input"
/>
</div>
</form>
<div>
<div>
<ul>
{paintBrandArr}
{paintColorArr}
{paintSheenArr}
</ul>
</div>
</div>
</div>
);
}
}
What you could do is map over one array and get info from all the three arrays through index like
var paintBrandArr = this.state.paintBrand;
paintBrandArr = paintBrandArr.map((brand, index) =>
<li key={brand}>
{brand}
{paintColorArr[index]}
{paintSheenArr[index]}
</li>
);
and then in render
<ul>
{paintBrandArr}
</ul>

How optimize HTML markup in react render

How I can optimize my HTML markup? In this case (I use Sublime Text 2), I choose "set syntax JSX" for highlighting and emeet won't work at first.
At second - more preferable for me, to keep markup in some .tmpl files.
It is possible in this case? For example, my render method:
render: function() {
var result = this.state.data;
var self = this;
var inputNodes = result.map && result.map(function(item, keyIndex) {
return (
<div className="row" key={keyIndex} className={'inputs-row ' + (item.disabled ? 'inputs-row_disabled':'')}>
<div className="col-md-12">
<div className="col-md-6 form-group">
<div className="input-group">
<div className="input-group-addon">
<i className="fa fa-info fa-fw"></i>
</div>
<input className="key-input form-control" type='text' value={item.name} onClick={self.onInputKeyClick.bind(self,item)} readOnly />
</div>
</div>
{
item.values.map(function(value, valIndex) {
return (
<div className="col-md-6 form-group" key={valIndex}>
<div className="input-group">
<input className="key-input form-control" type='text' value={value.name} onChange={self.changeLocalizedValue.bind(self, value, valIndex, keyIndex)} />
<div className="input-group-addon input-group-addon_btn">
<button className="btn btn-default btn_right-radius" onClick={self.sendItem.bind(self, value)}>
<i className="fa fa-check fa-fw"></i>
</button>
</div>
</div>
</div>
)
})
}
</div>
</div>
);
});
return (
<div>
<div>{inputNodes}</div>
<button onClick={self.sendAll}>SEND ALL</button>
</div>
)
}
P.S. I use: gulp and browserify.
There are libraries that lets you extract React templates into their own files, but I think one of the strengths of React is that the markup is co-located with the view logic. If the markup is changed then the view logic often has to be changed, and vice versa. Keeping them in the same file makes that more convienient.
I would recommend you to create more components. Take this chunk of JSX for example:
<div className="col-md-6 form-group">
<div className="input-group">
<div className="input-group-addon">
<i className="fa fa-info fa-fw"></i>
</div>
<input className="key-input form-control" type='text' value={item.name} onClick={self.onInputKeyClick.bind(self,item)} readOnly />
</div>
</div>
Does very little, and it's not very readable what the purpose of that chunk is. If you instead extract that into another component and give it a meaningful name, your markup won't look as cluttered, and you get better readability.

Categories