How to display validation messages with javascript alert window? - javascript

I use LogOn partial view on Index view and use default LogOnModel of MVC3. But, there is not enough place to display validation messages in view. How can I display validation messages with javascript alert window?
[HttpPost]
public ActionResult LogOn( LogOnModel model, string returnUrl )
{
if ( ModelState.IsValid )
{
if ( ( model.UserName != null ) && ( model.Password != null ) )
{
if ( Membership.ValidateUser( model.UserName, model.Password ) )
{
FormsAuthentication.SetAuthCookie( model.UserName, true );
if ( Url.IsLocalUrl( returnUrl ) && returnUrl.Length > 1 && returnUrl.StartsWith( "/" )
&& !returnUrl.StartsWith( "//" ) && !returnUrl.StartsWith( "/\\" ) )
{
return Redirect( returnUrl );
}
else
{
return RedirectToAction( "Index", "Home", model );
}
}
else
{
return RedirectToAction( "Index", "Home" );
}
}
else return RedirectToAction( "Index", "Home" );
}
return RedirectToAction( "Index", "Home" );
}
In Index view:
#Html.Partial( "LogOn" )
And LogOn view:
#model OnlineMarket.Models.LogOnModel
#using ( Html.BeginForm( "LogOn", "Home", FormMethod.Post ) )
{
#Html.ValidationSummary( true )
#Html.Hidden( "RememberMe", "true" )
<ul class="forms">
<li class="txt">Username</li>
<li class="inputfield">
#Html.TextBoxFor( m => m.UserName, new { #class = "logininputs" } )
</li>
</ul>
<ul class="forms">
<li class="txt" style="width: 26px;">Password</li>
<li class="inputfield">
#Html.TextBoxFor( m => m.Password, new { #class = "logininputs" } )
</li>
</ul>
<ul class="forms">
<li class="txt" style="width: 50px; margin-top: -5px; margin-left: 4px;">
<input type="submit" value="Enter" class="buttonforinput" style="height: 23px;" />
</li>
</ul>
}

For the unobtrusive client validation you could subscribe to the showErrors callback and display the errors the way you want (alert in your case):
(function ($) {
$.validator.setDefaults({
onsubmit: true,
onkeyup: false,
onfocusout: false,
showErrors: function (errorMap, errorList) {
if (errorList.length > 0) {
var errors = errorList.map(function (element) {
return element.message;
}).join('\r\n');
alert(errors);
}
}
});
})(jQuery);
In order to display server side errors with alert on the client you shouldn't be using the #Html.ValidationSummary( true ) helper because this helper outputs the errors directly in the view and you said that you don't have enough place.
So you could emit javascript dynamically when there are errors and display them in an alert:
#if (!ViewData.ModelState.IsValid)
{
<script type="text/javascript">
var errors = #Html.Raw(
Json.Encode(
string.Join(
Environment.NewLine,
ViewData.ModelState
.Where(x => x.Value.Errors.Count > 0)
.SelectMany(x => x.Value.Errors)
.Select(error => error.ErrorMessage))
)
);
alert(errors);
</script>
}

Related

ReactJS Conditional Rendering - else if doesn't work

I'm in the stage of learning JS and React and I'm not sure why else if doesn't work in the code below. Anyone can help me?
function Item({ name, isPacked }) {
if (isPacked) {
return (
<li className="item">
{name} {isPacked && " ✔"}
</li>
);
} else if (!isPacked) {
return (
<li className="item">
{name} {isPacked && " ❌"}
</li>
);
}
}
export default function PackingList() {
return (
<section>
<h1>Sally Ride's Packing List</h1>
<ul>
<Item isPacked={true} name="Space suit" />
<Item isPacked={true} name="Helmet with a golden leaf" />
<Item isPacked={false} name="Photo of Tam" />
</ul>
</section>
);
}
Try like this:
function Item({ name, isPacked }) {
return (
<li className="item">
{`${name} ${isPacked ? "✔" : '❌'} `}
</li>
);
}
you actually tested if the isPacked true or false so try this code:
function Item({ name, isPacked }) {
return (
<li className="item">
{name} {isPacked ? "✔" : "❌" }
</li>
);
}
{isPacked ? "✔" : "❌" } so this line of code is equal to:
if(isPacked == true){
return "✔";
}else{
return "❌";
}
You can get some helpful examples Here https://reactjs.org/docs/conditional-rendering.html.

How can i create hyperlinks within the map method?

I have an array of files and I want certain ones to be displayed and hyperlinked. I'm using the map method and when only 1 file displays, it links properly. I need some help with the syntax when multiple files must be displayed.
render() {
const mappings = {
'P1011': 'http://192.168.191.128:8080/Pickering-P1011-May-Verified_Results5.xls',
'P1511': 'http://192.168.191.128:8080/PNGS-1511-Verified_Results_2.xls',
'P1711': 'http://192.168.191.128:8080/PNGS-P1711_Verified_Results_3.xlsx',
'P1911': 'http://192.168.191.128:8080/PLGS_Unit_1-PL1911_VerifiedResults2.xlsx',
}
if (this.props.channelSelectedData.length >= 1){
return(
<div className="channel-detail-box">
<p>Outages:
<a href={mappings[this.props.channelSelectedData.map(inspection => {
return inspection.outage
})]}>
{this.props.channelSelectedData.map(inspection => {
return inspection.outage + ' '
})}</a>
</p>
</div>
)
}
else {
return (
<div>
<p>No data found</p>
</div>
)
}
}
}
Is this what you are looking for ?
render() {
const mappings = {
'P1011': 'http://192.168.191.128:8080/Pickering-P1011-May-Verified_Results5.xls',
'P1511': 'http://192.168.191.128:8080/PNGS-1511-Verified_Results_2.xls',
'P1711': 'http://192.168.191.128:8080/PNGS-P1711_Verified_Results_3.xlsx',
'P1911': 'http://192.168.191.128:8080/PLGS_Unit_1-PL1911_VerifiedResults2.xlsx',
}
const { channelSelectedData } = this.props
if (channelSelectedData.length === 0) {
return <div>
<p>No data found</p>
</div>
}
return <div className="channel-detail-box">
<p>Outages: {channelSelectedData.map(({ outage }) => <a href={mappings[outage]}>{outage}</a>)}</p>
</div>
}
const mappings = {
'P1011': 'http://192.168.191.128:8080/Pickering-P1011-May-Verified_Results5.xls',
'P1511': 'http://192.168.191.128:8080/PNGS-1511-Verified_Results_2.xls',
'P1711': 'http://192.168.191.128:8080/PNGS-P1711_Verified_Results_3.xlsx',
'P1911': 'http://192.168.191.128:8080/PLGS_Unit_1-PL1911_VerifiedResults2.xlsx',
};
if (!channelSelectedData || channelSelectedData.length <= 0) {
return (
<div>
<p>No data found</p>
</div>
);
}
const links = channelSelectedData.map(({ outage }) => (
<a href={mappings[outage]}>{outage}</a>
));
return (
<div className="channel-detail-box">
<p>Outages: {links}</p>
</div>
);
If I am understanding the rest of your question correctly, I believe your issue is just using map at the incorrect point. What map does is returns an array of values which in this case would be an array of applicable tags.
render() {
const mappings = {
'P1011': 'http://192.168.191.128:8080/Pickering-P1011-May-Verified_Results5.xls',
'P1511': 'http://192.168.191.128:8080/PNGS-1511-Verified_Results_2.xls',
'P1711': 'http://192.168.191.128:8080/PNGS-P1711_Verified_Results_3.xlsx',
'P1911': 'http://192.168.191.128:8080/PLGS_Unit_1-PL1911_VerifiedResults2.xlsx',
}
if (this.props.channelSelectedData.length >= 1){
return(
<div className="channel-detail-box">
<p>Outages:
<>
{
this.props.channelSelectedData.map(chanel=>{
return (
<a href={mappings[chanel]}>
{chanel+' '}
</a> )
})
}
</>
</p>
</div>
)
}
else {
return (
<div>
<p>No data found</p>
</div>
)
}
}

checkbox styling and making it checked

The checkbox retrieved from database is so long that it is going downwards, is there any way to make it as four layers
when clicked on "all fields" checkbox all checkbox must be checked.
How this to be done?
My code :-
protected function getConfigForm()
{
$sql = 'SELECT id_order_state,name FROM '._DB_PREFIX_.'order_state_lang';
$results = Db::getInstance()->ExecuteS($sql);
$values_query = array(array(
'id' => 'AllFields',
'name' => $this->l('All Fields'),
'val' => 'All',
));
foreach ($results as $row) {
$values_query[] = array(
'id' => 'OrderID',
'name' => $this->l($row['name']),
'val' => $row['id_order_state'],
'required' => true,
);
}
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'checkbox',
'label' => $this->l('Select Required Status'),
'required' => true,
'values' => array(
'query' => $values_query,
'id' => 'id',
'name' => 'name'
),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
Admin forms are rendered using /adminXXX/themes/default/template/helpers/form/form.tpl template file.
In classes /classes/helper/Helper.php there's a method createTemplate():
public function createTemplate($tpl_name)
{
if ($this->override_folder) {
if ($this->context->controller instanceof ModuleAdminController) {
$override_tpl_path = $this->context->controller->getTemplatePath().$this->override_folder.$this->base_folder.$tpl_name;
} elseif ($this->module) {
$override_tpl_path = _PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/_configure/'.$this->override_folder.$this->base_folder.$tpl_name;
} else {
if (file_exists($this->context->smarty->getTemplateDir(1).$this->override_folder.$this->base_folder.$tpl_name)) {
$override_tpl_path = $this->context->smarty->getTemplateDir(1).$this->override_folder.$this->base_folder.$tpl_name;
} elseif (file_exists($this->context->smarty->getTemplateDir(0).'controllers'.DIRECTORY_SEPARATOR.$this->override_folder.$this->base_folder.$tpl_name)) {
$override_tpl_path = $this->context->smarty->getTemplateDir(0).'controllers'.DIRECTORY_SEPARATOR.$this->override_folder.$this->base_folder.$tpl_name;
}
}
} elseif ($this->module) {
$override_tpl_path = _PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/_configure/'.$this->base_folder.$tpl_name;
}
if (isset($override_tpl_path) && file_exists($override_tpl_path)) {
return $this->context->smarty->createTemplate($override_tpl_path, $this->context->smarty);
} else {
return $this->context->smarty->createTemplate($this->base_folder.$tpl_name, $this->context->smarty);
}
}
As you can see in this method, you have the possibility to override a default admin template inside your module by creating this file /modules/my_module/views/templates/admin/_configure/helpers/form/form.tpl:
{extends file="helpers/form/form.tpl"}
{block name="input"}
{if $input.type == 'checkbox'}
{if isset($input.expand)}
<a class="btn btn-default show_checkbox{if strtolower($input.expand.default) == 'hide'} hidden{/if}" href="#">
<i class="icon-{$input.expand.show.icon}"></i>
{$input.expand.show.text}
{if isset($input.expand.print_total) && $input.expand.print_total > 0}
<span class="badge">{$input.expand.print_total}</span>
{/if}
</a>
<a class="btn btn-default hide_checkbox{if strtolower($input.expand.default) == 'show'} hidden{/if}" href="#">
<i class="icon-{$input.expand.hide.icon}"></i>
{$input.expand.hide.text}
{if isset($input.expand.print_total) && $input.expand.print_total > 0}
<span class="badge">{$input.expand.print_total}</span>
{/if}
</a>
{/if}
{* HERE WE DEFINE A CHECKBOX CHECK_ALL *}
<input type="checkbox" id="check_all" name="check_all" data-name="{$input.name}" value="1" />
{foreach $input.values.query as $value}
{assign var=id_checkbox value=$input.name|cat:'_'|cat:$value[$input.values.id]}
{* HERE YOU CAN REARRANGE THE CHECKBOXES AS YOU WANT *}
<div class="checkbox{if isset($input.expand) && strtolower($input.expand.default) == 'show'} hidden{/if}">
{strip}
<label for="{$id_checkbox}">
<input type="checkbox" name="{$id_checkbox}" id="{$id_checkbox}" class="{if isset($input.class)}{$input.class}{/if}"{if isset($value.val)} value="{$value.val|escape:'html':'UTF-8'}"{/if}{if isset($fields_value[$id_checkbox]) && $fields_value[$id_checkbox]} checked="checked"{/if} />
{$value[$input.values.name]}
</label>
{/strip}
</div>
{/foreach}
{else}
{$smarty.block.parent}
{/if}
{/block}
{* HERE WE DEFINE THE JAVASCRIPT THAT WILL ANIMATE THE CHECK ALL CHECKBOX *}
<script type="text/javascript">
$("#check_all").on('change', function() {
$("input[name=" + $(this).data('name') + "]").prop('checked', true);
$(this).prop('checked', false);
});
</script>
This template will be used for every admin controller defined in your module.
I didn't test this code, you'll have to adapt it to your needs but the overall concept is here.

How to get the inputbox entered value as component in the parent class reactJS

I have created InputField and button as separate component and make use of in the two js files incomeFields and Emifields. Then the two Js file as a component called in mail file called HomeLoanEmiCalculator. Then another file success file to calculate based on the input provided. on click of next button the value will be save in one object and we can retreive the entered value inside the success file to calculate the EMI values. I refer the site below https://www.online.citibank.co.in/products-services/loans/pop-up/home-loan-eligibility-calculator.htm
as we have to create in ReactJS. Below code not working properly. Even am using ref i cannot able to access the fieldvalues
var React = require('react');
var InputField = React.createClass({
getInitialState: function(){
return{
value: this.props.value || '',
};
},
setValue: function (event) {
this.setState({
value: event.currentTarget.value
});
setDefaultValue = this.props.fieldValues+"."+this.props.stateId;
},
render: function() {
return (<div>
<div>
<input className="inputText" id={this.props.stateId} type="text"
ref={this.props.stateId} onChange={this.props.setValue} defaultValue={this.props.setDefaultValue}/>
</div>);
}
});
module.exports = InputField;
var React = require('react')
var InputField = require('./InputField')
var IncomeFields = React.createClass({
nextStep: function(e) {
e.preventDefault();
var data = {
monthlyIncome : this.refs.monthlyIncome.getDOMNode().value,
rentalIncome : this.refs.rentalIncome.getDOMNode().value,
otherIncome : this.refs.otherIncome.getDOMNode().value
}
this.props.saveValues(data);
this.props.nextStep();
},
render: function() {
return (<div>
<h2>Please enter your income details</h2>
<ul className="inputList">
<li className="width25 hlec">
<InputField name="Gross Monthly Income"
stateId="monthlyIncome"
metrics= "INR"
required="true"
setDefaultValue={this.props.fieldValues.monthlyIncome}
imgPath="images/icons/icon_rupee.png"/>
</li>
<li className="width25 hlec">
<InputField name="Rental Income"
stateId="rentalIncome"
metrics= "INR"
setDefaultValue={this.props.fieldValues.rentalIncome}
imgPath="images/icons/icon_house.png"/>
</li>
<li className="width25 hlec last">
<InputField name="Other Income"
stateId="otherIncome"
metrics= "INR"
setDefaultValue={this.props.fieldValues.otherIncome}
imgPath="images/icons/icon_cashBundle.png"/>
</li>
</ul>
</div>
)
}
})
module.exports = IncomeFields
var React = require('react')
var InputField = require('./InputField')
var EmiFields = React.createClass({
nextStep: function(e) {
e.preventDefault();
var data = {
mortageLoan : this.refs.mortageLoan.getDOMNode().value,
persoanlLoan : this.refs.persoanlLoan.getDOMNode().value,
creditLoan : this.refs.creditLoan.getDOMNode().value,
autoLoan : this.refs.autoLoan.getDOMNode().value,
outstandingCCAmount : this.refs.outstandingCCAmount.getDOMNode().value,
interestRate : this.refs.interestRate.getDOMNode().value
}
this.props.saveValues(data);
this.props.nextStep();
},
render: function() {
return (<div>
<h2>Please enter your income details</h2>
<ul className="inputList">
<li className="width25 hlec">
<InputField name="Any other Mortgage Loan"
stateId="mortageLoan"
metrics= "INR"
imgPath="images/icons/icon_house.png"/>
</li>
<li className="width25 hlec">
<InputField name="Personal Loan"
stateId="personalLoan"
metrics= "INR"
imgPath="images/icons/icon_user.png"/>
</li>
<li className="width25 hlec">
<InputField name="Loan on Credit Card"
stateId="creditLoan"
metrics= "INR"
imgPath="images/icons/icon_card.png"/>
</li>
<li className="width25 hlec last">
<InputField name="Auto Loan"
stateId="autoLoan"
metrics= "INR"
imgPath="images/icons/icon_car.png"/>
</li>
</ul>
<ul className="inputList part2">
<li className="width25 hlec">
<InputField name="Outstanding Amount on Credit Card"
stateId="outstandingCCAmount"
metrics= "INR"
imgPath="images/icons/icon_rupee.png"/>
</li>
<li className="width25 hlec last">
<InputField name="Auto Loan"
stateId="otherLoan"
metrics= "INR"
imgPath="images/icons/icon_rupee.png"/>
</li>
</ul>
</div>
)
}
})
module.exports = EmiFields
var React = require('react');
var EmiCalculations = require('./store/EmiCalculator');
var aboutLoanStyle = {
width: '235px',
marginRight: '10px'
};
var loanAvail = null;
var homeValue = null;
var monthlyEMI = null;
var Success = React.createClass({
render: function() {
return (
<div> {this.calculate}
<div className="section1 outputSection">
<ul className="outputRack">
<li className="c2">
<div className="outputLabel">
<strong>Maximum Home Loan available to you</strong>
</div>
<div className="outputValue last" id="loanAvail" ref="loanAvail" defaultValue={this.props.fieldValues.loanAvail}>{EmiCalculations.getLoanAvail(this.props.fieldValues)}</div>
</li>
<li className="c2 last">
<div className="outputLabel">
<strong>Value of Home you can purchase</strong>
</div>
<div className="outputValue last" id="homevalue" ref="homeValue" defaultValue={this.props.fieldValues.homeValue}>{EmiCalculations.getHomeValue(this.props.fieldValues)}</div>
</li>
</ul>
<ul className="outputRack rack2">
<li className="c2">
<div className="outputLabel">
<strong>Your Monthly EMI</strong>
</div>
<div className="outputValue last" id="monthlyEMI" ref="monthlyEMI" defaultValue={this.props.fieldValues.monthlyEMI}>{EmiCalculations.getMonthlyEMI(this.props.fieldValues)}</div>
</li>
</ul>
</div>
</div>
)
}
})
module.exports = Success
var React = require('react')
var IncomeFields = require('./IncomeFields')
var aboutLoanStyle = {
width: '235px',
marginRight: '10px'
};
var Navigation = React.createClass({
getInitialState: function() {
return {
nextCount: 1
}
},
nextStep: function(e) {
e.preventDefault();
var cnt = ++this.state.nextCount
this.props.nextStep(cnt);
this.setState({nextCount: cnt});
console.log(IncomeFields.props.fieldValues);
},
render: function() {
return (<div className="inputButtonSection">
<div className="right step1">
<button className="blueBtn" style={aboutLoanStyle}>KNOW MORE ABOUT HOME LOANS</button>
{this.props.nextBtnVisibility ? <button key={this.state.showEmiField} className="blueBtn nextBtn" style={this.props.btnStyle} onClick={this.nextStep}>{this.props.nextStepLabel}</button> : null}
{this.props.resetBtnVisibility ? <button className="greyBtn reset first" onClick={this.resetValues}>RESET</button> : null }
</div>
</div>
)
}
})
module.exports = Navigation
var React = require('react')
var IncomeFields = require('./IncomeFields')
var EmiFields = require('./EmiFields')
var Success = require('./Success')
var assign = require('object-assign')
var Navigation = require('./Navigation')
var fieldValues = {
principalAmount : 100000,
monthlyIncome: null,
rentalIncome : null,
otherIncome : null,
mortageLoan : null,
persoanlLoan : null,
creditLoan : null,
autoLoan : null,
outstandingCCAmount : null,
otherLoan : null,
downPayment : null,
loanTenure : null,
loanAvail: null,
homeValue: null,
monthlyEMI: null
};
var HomeLoanEMICalculator = React.createClass({
getInitialState: function() {
return {
nextStepCount: 1,
nextStepLabel: "NEXT",
showEmiField: false,
showTenureFields: false,
showOutput: false,
nextBtnVisibility: true,
resetBtnVisibility: false,
btnStyle : {
marginRight: '10px'
}
}
},
saveValues: function(field_value) {
return function() {
fieldValues = assign({}, fieldValues, field_value)
}.bind(this)()
},
nextStep: function(count) {
//this.setState({nextStepCount: count});
this.showNext(count, true);
},
showNext: function(c, bool) {
if(c===2) {
this.setState({resetBtnVisibility : bool});
this.setState({showEmiField: bool});
} else if(c===3) {
this.setState({showTenureFields: bool});
this.setState({nextStepLabel: "CALCULATE"});
btnStyles = {
width: '110px',
marginRight: '10px'
}
this.setState({btnStyle: btnStyles});
} else if(c===4) {
this.setState({showOutput: bool});
this.setState({nextBtnVisibility: false});
}
},
render: function() {
return (
<div className="calculatorWrapper">
<IncomeFields fieldValues={fieldValues}
nextStep={Navigation.nextStep}
saveValues={this.saveValues}/>
{this.state.showEmiField ? <EmiFields fieldValues={fieldValues}
nextStep={Navigation.nextStep}
saveValues={this.saveValues}/>: null}
{this.state.showOutput ? <Success fieldValues={fieldValues}/> : null}
<Navigation nextBtnVisibility={this.state.nextBtnVisibility} resetBtnVisibility={this.state.resetBtnVisibility} btnStyle={this.state.btnStyle} nextStepLabel={this.state.nextStepLabel} nextStep={this.nextStep}/>
</div>
)
}
})
module.exports = HomeLoanEMICalculator
var React = require('react')
var ReactDOM = require('react-dom')
var HomeLoanEMICalculator = require('./components/HomeLoanEMICalculator')
window.onload = function() {
ReactDOM.render(
<HomeLoanEMICalculator />,
document.getElementById('emi-calc-form')
)
}
Please help me to do this. pls thanks in advance
There are a few problems with what you are trying to do:
If you read the documentation on refs:
https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute
You will see that you need to assign a ref attribute on the component you want to get the DOM value for.
this.refs.monthlyIncome.getDOMNode().value
only works if you do something like:
<input className="inputText" type="text" ref="monthlyIncome" />
One way of tackling this is to have the fields be properties in a state, and based on whether those states are set, trigger your form to move into it's next state. You probabl
The code may resemble something like below. You still need to implement functions so that onChange will update the state. You can easily replace input with InputField if input field takes the value via props, and the onChange function comes back up to change the state.
var InputField = React.createClass({
getInitialState: function(){
return {mortgageLoan: null, principalAmount: null};
},
renderFirstForm: function() {
return (
<div>Mortgage Loan: <input className="inputText" value={this.state.mortgageLoan} /></div>
)
},
firstFormComplete: function() {
return (this.state.mortgageLoan != null);
}
renderSecondForm: function() {
return (
<div>Principal Amount: <input className="inputText" value={this.state.principalAmount} onChange={} /></div>
)
}
})

"this" is undefined inside map function Reactjs

I'm working with Reactjs, writing a menu component.
"use strict";
var React = require("react");
var Menus = React.createClass({
item_url: function (item,categories,articles) {
console.log('afdasfasfasdfasdf');
var url='XXX';
if (item.type == 1) {
url = item.categoryId == null ? 'javascript:void(0)' : path('buex_portal_browse_category', {slug: categories[item.categoryId].slug});
} else if (item.type == 2) {
url = item.articleId == null ? 'javascript:void(0)' : path('buex_portal_view_article', {slug: articles[item.articleId].slug, id: item.articleId});
} else {
url = item.url;
}
return url;
},
render: function () {
// console.log(this.props.menus); // return correctly
var menuElements = this.props.menus.map(function (item1) { // return fault : 'cannot read property 'props' of undefined '
return (
<div>
<li>
<a href={this.item_url(item1, this.props.categories, this.props.articles )}>{item1.name} // the same fault above
<i class="glyphicon glyphicon-chevron-right pull-right"></i>
</a>
<div class="sub-menu">
<div>
{item1._children.map(function (item2) {
return (
<div>
<h4>
<a href={this.item_url(item2, this.props.categories, this.props.articles)}>{ item2.name }</a>
</h4>
<ul>
{item2._children.map(function (item3) {
return (
<div><li><a href={this.item_url(item3, this.props.categories, this.props.articles) }>{ item3.name }</a></li></div>
);
})}
</ul>
</div>
);
})}
</div>
</div>
</li>
</div>
);
});
return (
<div class="menu">
<ul class="nav nav-tabs nav-stacked">
{menuElements}
</ul>
</div>
);
}
});
Whenever I use 'this' inside map function it is undefined, but outside it is no problem.
The error:
"Cannot read property 'props' of undefined"
Anybody help me ! :((
Array.prototype.map() takes a second argument to set what this refers to in the mapping function, so pass this as the second argument to preserve the current context:
someList.map(function(item) {
...
}, this)
Alternatively, you can use an ES6 arrow function to automatically preserve the current this context:
someList.map((item) => {
...
})

Categories

Resources