Calling a function inside render function - ReactJS? - javascript

Ok so I am making a "buzzfeed" quiz generator and I am having an issue with a piece of my form. So for each question made there are two different parts, a "Question" and the "Answers". There will always be 4 answers but I want to keep track of which Answers are checked later so I would like to give each answer a unique id "question" + questionNum + "Answer" + answerNum or "question" + questionNum + "Answer" + i So I made this answersGenerator function that is supposed to give me 4 unique answer choice fill ins for the user to input answers for that specific questions (right now it says something about terms and conditions - ignore that I ad just left it like that for now because I was following a tutorial). Here is all my code:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import logo from './logo.svg';
import './App.css';
var questionNum = 1;
var answerNum = 1;
class App extends Component {
constructor(props) {
super(props);
this.state = {
quizTitle: "",
author: "",
question: "",
terms: false,
test: "",
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
event.preventDefault();
console.log(this.state);
}
render() {
return (
<div className="App">
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
<div className="container">
<div className="columns">
<div className="formDiv">
<form className="form" onSubmit={this.handleSubmit}>
<div className="field">
<label className="label">Give your quiz a title.</label>
<div className="control">
<input
className="input"
type="text"
name="quizTitle"
value={this.state.quizTitle}
onChange={this.handleChange}
/>
</div>
</div>
<div className="field">
<label className="label">Who's the Author?</label>
<div className="control">
<input
className="input"
type="text"
name="author"
value={this.state.author}
onChange={this.handleChange}
/>
</div>
</div>
<div className="questions" id="questions">
<div className="question" id={'questionGroup' + questionNum}>
<div className="field">
<label className="label" id={'question' + questionNum}>Question {questionNum}</label>
<div className="control">
<input
className="input"
type="text"
name='question'
value={this.state.question}
onChange={this.handleChange}
/>
</div>
</div>
<div className="answersDiv">
<label className="label">Answers</label>
<div className="field">
<div className="control">
<label className="checkbox">
{this.answersGenerator()}
</label>
</div>
</div>
</div>
</div>
</div>
<div className="field">
<div className="endButtons">
<button id="addQuestionButton"
onClick={addQuestion}>Add Question</button>
<input
type="submit"
value="Submit"
id="submitButton"
className="button is-primary"
/>
</div>
</div>
</form>
</div>
<div className="column is-3">
<pre>
<code>
<p>Quiz Title: {this.state.quizTitle}</p>
<p>Author: {this.state.author}</p>
<p>Question: {this.state.question}</p>
<p>Terms and Condition: {this.state.terms}</p>
<p>Do you test?: {this.state.test}</p>
</code>
</pre>
</div>
</div>
</div>
</div>
);
}
}
function answersGenerator () {
console.log("hello this is answer generator");
var div = document.createElement('div');
div.className = 'answers' + {questionNum};
for (var i = 1; i < 5; i++){
div.innerHTML =
'<div className="field">\
<div className="control">\
<label className="checkbox">\
<label className="label">Answers</label>\
<input\
name="terms"\
type="checkbox"\
id="question'+{questionNum}+'Answer'+{i}+'"\
checked={this.state.terms}\
onChange={this.handleChange}\
/>\
I agree to the{" "}\
terms and conditions\
</label>\
</div>';
document.getElementsByClassName('answersDiv')[0].appendChild(div)
}
}
function addQuestion () {
questionNum++;
console.log(questionNum + "that is the question number");
var div = document.createElement('div');
div.className = "questions" + questionNum;
div.innerHTML =
'<div id="questionGroup'+{questionNum}+'">\
Question '+{questionNum}+'<br />\
<input type="text" name="question'+{questionNum}+'"/><br />\
Answers<br />\
Check the box(es) for the correct answer(s).<br />\
<input type="checkbox" name="question'+{questionNum}+'Answer1Box" />\
<label for="question'+{questionNum}+'Answer1"><input type="text" name="question'+{questionNum}+'Answer1"/></label><br />\
<input type="checkbox" name="question'+{questionNum}+'Answer2Box" id= />\
<label for="question'+{questionNum}+'Answer2"><input type="text" name="question'+{questionNum}+'Answer2"/></label><br />\
<input type="checkbox" name="question'+{questionNum}+'Answer3Box" />\
<label for="question'+{questionNum}+'Answer3"><input type="text" name="question'+{questionNum}+'Answer3"/></label><br />\
<input type="checkbox" name="question'+{questionNum}+'Answer4Box" />\
<label for="question'+{questionNum}+'Answer4"><input type="text" name="question'+{questionNum}+'Answer4"/></label><br />\
</div>';
document.getElementsByClassName('questions')[0].appendChild(div)
}
export default App;
There's a few things to just ignore in here, i just wasn't sure how much info you needed. So the issue is that I get an error when I call my answersGenerator function in my render function. Here's the error Uncaught TypeError: this.answersGenerator is not a function Here's the small piece where that is
<div className="answersDiv">
<label className="label">Answers</label>
<div className="field">
<div className="control">
<label className="checkbox">
{this.answersGenerator()}
</label>
</div>
</div>
</div>
I appreciate the help, if you have any other tips for me other than this issue I am having I am all ears. I am very new at this, being js and React.
UPDATE: I have edited the answersDiv to be just this (I relized it was being called inside a checkbox)
<div className="answersDiv">
<label className="label">Answers</label>
{answersGenerator()}
</div>
I am still getting the same errors though.

You're receiving the error because the answersGenerator() isn't a method of your class App, so, you can't refer to it using this. If you want to do on that way, move you function to inside the component, like this:
class App extends Component {
// your component definition etc..
answersGenerator = () => {
// your function implementation
}
// the rest of your component
}
TIP:
If you dont want to have to always bind the function, like:
this.handleChange = this.handleChange.bind(this);
Declare your method like:
handleChange = (event) => { // the implementation }
Instead of
handleChange(event) { // the implementation }
The () => {}, known as arrow function, does the bind for your.
EDIT
You're developing with React, that supports creating HTML inside your code. So, you can create an array of answers, then, return a div with the answers mapped inside. The map will take each answer and render inside the div. Try to define your method as below:
answersGenerator => () {
console.log("hello this is answer generator");
var answers = []
for (var i = 1; i < 5; i++){
answers.push(
<div className="field">
<div className="control">
<label className="checkbox">
<label className="label">Answers</label>
<input
name="terms"
type="checkbox"
id=`question${questionNum}Answer${i}`
checked={this.state.terms}
onChange={this.handleChange}
/>
I agree to the{" "}
terms and conditions
</label>
</div>
);
}
return <div className=`answer${questionNum}`> {answers.map(answer => answer)} </div>
}

At first glance it looks like you haven't defined your answersGenerator() function within your App class.
Thus, this.answersGenerator() doesn't exist.
Try just using answersGenerator() without the this.

Related

Submitting Checkbox Form data in React. (amongst other data)

Example Form So Far
This is my current code that works, without any checkbox handling started.
import React, { useState } from "react";
import "../admin/SysHealthForm.scss";
export default function SysHealthForm() {
const [input, setInput] = useState({
header: "",
content: "",
eta: "",
});
//When any change is registered, update the Name + Value with target.
//Return previous text and display as name: entered value
function handleChange(e) {
const { name, value } = e.target;
setInput((prevInput) => {
return {
...prevInput,
[name]: value,
};
});
}
//Stop Page Refreshing and Console.log the JSON
function handleClick(e) {
e.preventDefault();
console.log(input);
}
return (
<div className="widgit-syshealth">
<h2>System Health</h2>
<form>
<input
name="header"
placeholder="Header"
autoComplete="off"
onChange={handleChange}
value={input.header}
required
></input>
<textarea
name="content"
placeholder="Message"
autoComplete="off"
onChange={handleChange}
value={input.content}
required
></textarea>
<div className="form-school-check">
<div>
<input type="checkbox" id="syshpcb1" value="Fosseway"></input>
<label htmlFor="syshpcb1">Fosse Way</label>
</div>
<div>
<input type="checkbox" id="syshpcb2" value="Mendip"></input>
<label htmlFor="syshpcb2">Mendip</label>
</div>
<div>
<input type="checkbox" id="syshpcb3" value="Nunney"></input>
<label htmlFor="syshpcb3">Nunney</label>
</div>
<div>
<input type="checkbox" id="syshpcb4" value="Hayesdown"></input>
<label htmlFor="syshpcb4">Hayesdown</label>
</div>
<div>
<input type="checkbox" id="syshpcb5" value="Moorlands"></input>
<label htmlFor="syshpcb5">Moorlands</label>
</div>
<div>
<input type="checkbox" id="syshpcb6" value="Cameley"></input>
<label htmlFor="syshpcb6">Cameley</label>
</div>
<div>
<input type="checkbox" id="syshpcb7" value="St Mary's"></input>
<label htmlFor="syshpcb7">St Mary's</label>
</div>
<div>
<input type="checkbox" id="syshpcb8" value="Other"></input>
<label htmlFor="syshpcb8">Other</label>
</div>
</div>
<input
placeholder="ETA For Fix"
onChange={handleChange}
value={input.eta}
name="eta"
></input>
<button type="Submit" onClick={handleClick}>
Submit
</button>
</form>
</div>
);
}
At The Moment, when you submit the data. It logs the header, content and eta etc correctly
but i want it to essentially create an Array of all the checkboxes that are ticked.
I just don't know where i would even begin..
Will be pushing the data back up to a MongoDB Atlas database once recieved.
Thanks

React multiple modal in one web page with different buttons

The advanced Search modal and the add modal are not opening at all. I am learning react for the first time so please help. Thanking you in advance.
App.js:
import React,{ useState } from 'react'
import Logo from './components/Logo.js'
import './App.css'
import PredictBtn from './components/PredictBtn.js'
import Analytics from './components/AnalyticsView.js'
import Advsrchmodal from './components/Advsrchmodal.js'
import Search from './components/Search.js'
import Add from './components/Addmodal.js'
export default function App(){
const [showAdd, setShowAdd] = useState(false);
const [showAdvanced, setShowAdvanced] = useState(false);
return(
<div>
<body>
<Logo />
<div className='header-btns'>
<PredictBtn/><Analytics/>
<button onClick={()=> setShowAdvanced(true)} className="leftbtns adv-srch-btn"id="adv-srch-modal">ADVANCED SEARCH</button>
<Advsrchmodal onClose={()=> setShowAdvanced(false)} show={showAdvanced}/>
<Search />
<button onClick={()=> setShowAdd(true)} className="rightbtns add-btn" id ="add-modal">ADD</button>
<Add onClose={()=> setShowAdd(false)} show={showAdd}/>
</div>
</body>
</div>
)
}
Add Modal.js:
import React from 'react'
const Addmodal= props => {
if(!props.showAdd){
return null
}
return (
<div className='modal overlay' id= 'add-modal '>
<div className="modal-content" id= 'add-modal '>
<div className="modal-header" id= 'add-modal '>
<h4 className="modal-title" id= 'add-modal '>Add</h4>
</div>
< div className="modal-body" id= 'add-modal '>
<input type="text" placeholder='Document ID' id='doc_id' className="modal-input" />
<input type="text" placeholder='Invoice Id' id='invoice_id' className="modal-input" />
<input type="text" placeholder='Customer Number' id='cust_number' className="modal-input" />
<input type="text" placeholder='Business Year' id='business_year' className="modal-input" />
<input type="text" placeholder='Document ID' id='doc_id' className="modal-input" />
<input type="text" placeholder='Invoice Id' id='invoice_id' className="modal-input" />
<input type="text" placeholder='Customer Number' id='cust_number' className="modal-input" />
<input type="text" placeholder='Business Year' id='business_year' className="modal-input" />
</div>
<div className="modal-footer" id= 'add-modal '>
<button className="addbtn " id= 'add-modal '>ADD</button>
<button className="cancel" id= 'add-modal ' onClick={props.onClose}>CANCEL</button>
</div>
</div>
</div>
)
}
export default Addmodal
Advsrchmodal.js:
import React from 'react'
const Advsrchmodal = props=> {
if(!props.showAdvanced){
return null
}
return (
<div className='modal overlay' id="adv-srch-modal" >
<div className="modal-content"id="adv-srch-modal">
<div className="modal-header"id="adv-srch-modal">
<h4 className="modal-title"id="adv-srch-modal"> Advance Search</h4>
</div>
< div className="modal-body"id="adv-srch-modal">
<input type="text" placeholder='Document ID' id='doc_id' className="modal-input" />
<input type="text" placeholder='Invoice Id' id='invoice_id' className="modal-input" />
<input type="text" placeholder='Customer Number' id='cust_number' className="modal-input" />
<input type="text" placeholder='Business Year' id='business_year' className="modal-input" />
</div>
<div className="modal-footer"id="adv-srch-modal">
<button className="advsrchbtn"id="adv-srch-modal">SEARCH</button>
<button className="cancel"id="adv-srch-modal" onClick={props.onClose}>CANCEL</button>
</div>
</div>
</div>
)
}
export default Advsrchmodal
The advanced Search modal and the add modal are not opening at all. I am learning react for the first time so please help. Thanking you in advance.
You are passing the props as show so you have to access it with its name
if(!props.show){
return null
}
try this in both modal components
You should remove most of the code and try to understand what is happening. Go with piece by piece. Your basic idea seems to be okay, but it is lacking some knowledge on the react side. What I would do is that the parent view is responsible for showing the modal and not the component itself. Just look at my simple example which I created https://codesandbox.io/s/cold-shape-wqv1by?file=/src/ModalEample.jsx
use state for toggling if the modal is open or not. Use the main view for deciding if the modal should be seen or not. Then pass the toggle to the modal component. Use destructuring for getting the props. I suppose most of the stuff are new for you, but to understand what is happening and why you should first remove some code and go with piece by piece. Remove the other modal and start working with only one modal.

React + EmailJS is sending me tons of emails in onClick method

I'm new to web development in general but I'm trying to create my own Contact page on my website and I'm having trouble. I'm using React, Gatsby, and Emailjs. I have my form set up so that the inputs are passed into the state onChange. Then I have a "send message" button that should send an email using EmailJS using the tokens and the state vars. This does all work and the email sends successfully, but it's sending dozens of emails. I believe what's happening is it's calling sendEmail every time the state is set and the DOM re-renders, or basically once for each character that's input into the fields, but I don't know why.
Bonus points if you can help me figure out why pressing the send message button also sends me to a 404 /# route on my site.
import React from 'react'
import emailjs from 'emailjs-com
class Main extends React.Component {
constructor(){
super()
this.state = {
fromName:'',
message:'',
fromEmail:''
}
}
render() {
return (
<div ...
>
...
<article>
...
<form method="post" action="#">
<div className="field half first">
<label htmlFor="name">Name</label>
<input type="text" name="name" id="name" value={this.state.fromName} onChange={e => this.setState({fromName: e.target.value})}/>
</div>
<div className="field half">
<label htmlFor="email">Email</label>
<input type="text" name="email" id="email" value={this.state.fromEmail} onChange={e => this.setState({fromEmail: e.target.value})}/>
</div>
<div className="field">
<label htmlFor="message">Message</label>
<textarea name="message" id="message" rows="4" value={this.state.message} onChange={e => this.setState({message: e.target.value})}
placeholder = "..."></textarea>
</div>
<ul className="actions">
<li>
<input type="submit" value="Send Message" className="special" onClick={this.sendEmail()}/>
</li>
</ul>
</form>
</article>
</div>
)
}
sendEmail() {
const serviceId='...'
const templateId='...'
const userId='...'
emailjs.send(serviceId, templateId, this.state, userId)
}
}
export default Main
The issue is that you never followed the emailjs documentation well and you never prevented the default form action.
According to the emailjs documentation you should have set the onClick function with the send email function (without invoking it) on the form's opening tag NOT on your submit button. (but the button is still necessary so that it can send the sign that the form needs to be submitted). You also invoked the sendEmail function which is inappropriate and leads to problems.
You must also add event as a parameter in your sendEmail function when creating this function. Then inside the sendEmail function call the event.preventDefault() function .
import React from 'react'
import emailjs from 'emailjs-com
class Main extends React.Component {
constructor(){
super()
this.state = {
fromName:'',
message:'',
fromEmail:''
}
}
render() {
return (
<div>
<article>
<form method="post" onClick={this.sendEmail} action="#">
<div className="field half first">
<label htmlFor="name">Name</label>
<input type="text" name="name" id="name" value={this.state.fromName} onChange={e => this.setState({fromName: e.target.value})}/>
</div>
<div className="field half">
<label htmlFor="email">Email</label>
<input type="text" name="email" id="email" value={this.state.fromEmail} onChange={e => this.setState({fromEmail: e.target.value})}/>
</div>
<div className="field">
<label htmlFor="message">Message</label>
<textarea name="message" id="message" rows="4" value={this.state.message} onChange={e => this.setState({message: e.target.value})}
placeholder = "..."></textarea>
</div>
<ul className="actions">
<li>
<input type="submit" value="Send Message" className="special"/>
</li>
</ul>
</form>
</article>
</div>
)
}
sendEmail(event) {
event.preventDefault();
const serviceId='...'
const templateId='...'
const userId='...'
emailjs.send(serviceId, templateId, this.state, userId)
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
}
}
export default Main

How can you add styles in reactJs for show/hiding google maps?

I have three radio buttons which chooses school, restaurant and store. When clicking each, I would like to display the following nearby place whether it is school, restaurant or store. I have no problem on displaying the google map and its nearby places if I do it individually.
class PropertyMap extends React.Component{
constructor(props) {
super(props);
this.state = {
propertyType: 'default',
selectedOption: ''
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
this.setState({
propertyType: e.target.value
});
}
componentDidMount(){
let school = document.getElementById('school');
let restaurant = document.getElementById('restaurant');
let default = document.getElementById('default');
if(this.state.propertyType == 'restaurant'){
school.setAttribute('style', 'height:0');
restaurant.setAttribute('style', 'height:100%');
}
else if(this.state.propertyType == 'school'){
school.setAttribute('style', 'height:100%');
restaurant.setAttribute('style', 'height:0');
}
else{
school.setAttribute('style', 'height:0%');
restaurant.setAttribute('style', 'height:0');
default.setAttribute('style', 'height:100%');
}
}
render(){
let _standard = this.props.standard;
let datax = _standard.data;
let address = datax.address;
let city = datax.City;
let postcode = datax.Code;
let st = datax.State;
let defaultMap = (<DefaultMap mapdetails={datax} />);
let schoolMap = (<SchoolMap mapdetails={datax} type={this.state.propertyType} />);
let restaurantMap = (<RestaurantMap mapdetails={datax} type={this.state.propertyType} />);
return(
<div>
<div className="container">
<div className="row">
<div className="col-md-12">
<div className="location-info-container">
<h2>Location</h2>
<p>
{address}.
</p>
<p>
{city}, {st} {postcode}
</p>
<p><b>Nearby:</b></p>
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="school" /> School
</label>
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="restaurant" /> Restaurant
</label>
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="store" /> Store
</label>
</div>
</div>
</div>
</div>
<div id="gmap">
<div id="default">
{defaultMap}
</div>
<div id="restaurant">
{restaurantMap}
</div>
<div id="school">
{schoolMap}
</div>
</div>
</div>
)
}
}
Can anyone advise why the styles from my componentDidMount are not updating when I click any of the radio buttons? Basically, if I click school I want its height to be equal to 100% and the restaurant to be 0 and vice-versa.
Like I said in a comment before, componentDidMount only executes the first time when component is mounted. You can use componentWillUpdate or componentDidUpdate if you need to do something before and/or after a component update. See: https://facebook.github.io/react/docs/react-component.html
If you just want to show or hide a component with a radio button action, best practice in React could be something like this:
class PropertyMap extends React.Component {
constructor(props) {
super(props);
this.state = {
propertyType: 'default',
selectedOption: ''
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
this.setState({
propertyType: e.target.value
});
}
render() {
let map = <div>Your Default component here</div>;
switch (this.state.propertyType) {
case 'restaurant':
map = <div>Your Restaurant component here</div>;
break;
case 'school':
map = <div>Your School component here</div>;
break;
}
return(
<div>
<div className="container">
<div className="row">
<div className="col-md-12">
<div className="location-info-container">
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="school" /> School
</label>
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="restaurant" /> Restaurant
</label>
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="store" /> Store
</label>
</div>
</div>
</div>
</div>
<div id="gmap">{map}</div>
</div>
)
}
}
// Render it
ReactDOM.render(
<PropertyMap />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
But if you want to use the height method, maybe something like this is better (using style and class attribute)
class PropertyMap extends React.Component {
constructor(props) {
super(props);
this.state = {
propertyType: 'default',
selectedOption: ''
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
this.setState({
propertyType: e.target.value
});
}
render() {
const { propertyType } = this.state
return(
<div>
<div className="container">
<div className="row">
<div className="col-md-12">
<div className="location-info-container">
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="school" /> School
</label>
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="restaurant" /> Restaurant
</label>
<label className="radio-inline">
<input type="radio" name="map" id="" onChange={this.handleClick} value="store" /> Store
</label>
</div>
</div>
</div>
</div>
<div id="gmap">
{/*
<div style={{height: (propertyType === 'restaurant') ? '100%' : '0%'}}>Your Restaurant component here</div>
<div style={{height: (propertyType === 'school') ? '100%' : '0%'}}>Your School component here</div>
<div style={{height: (propertyType !== 'restaurant' && propertyType !== 'school') ? '100%' : '0%'}}>Your Default component here</div>
*/}
<div className={(propertyType === 'restaurant') ? 'show' : 'hide'}>Your Restaurant component here</div>
<div className={(propertyType === 'school') ? 'show' : 'hide'}>Your School component here</div>
<div className={(propertyType !== 'restaurant' && propertyType !== 'school') ? 'show' : 'hide'}>Your Default component here</div>
</div>
</div>
)
}
}
// Render it
ReactDOM.render(
<PropertyMap />,
document.getElementById("root")
);
.show {
width: 100%;
display: block;
}
.hide {
width: 0%;
display: none;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
I could not upvote the comment earlier so I'll just post the solution here. As advised, I put all my code from the componentDidMount into the render function and it worked.

Render array of inputs in react

I have an array of emails (as a part of a bigger model). These are displayed in seperate rows witha remove button for each (the address itself can be updated in the input box directly). Unfortunately I dont know how to do this in react when the inputs are renderd using a map function.
(I am converting a meteor blaze project to meteor react).
Everything renders but how do I attach to change event so I can update my array of emails? onChange + value need to be set somehow.
This is the map function
return this.data.emailGroup.emails.map((email) => {
return (
<div key={email} className="input-group">
<input type="text" className="form-control" onChange={self.handleEmailListChange} value={email}/>
<div className="input-group-btn">
<button type="button"
className="btn btn-default remove-email"><span
className="glyphicon glyphicon-remove"></span></button>
</div>
</div>
);
});
The initial state(which is populated with data from the db:
getInitialState() {
return {
name : '',
description: '',
emails : [],
newEmailAddress : ''
}
},
Upon request here is the render method(it requires a getContent method.The getcontent method is there because in meteor I need to wait for data so in the meantime I need a loading state.
getContent() {
return (
<div className="box box-success">
<div className="box-header with-border">
<h3 className="box-title">List of emails</h3>
</div>
<form role="form" className="form-horizontal">
<div className="box-body">
<p>Below is a list of email addresses which are added to this email group. If
you
want
to add more
you can add them one by one by inputting in the box below or add a list into
the
same box (email
addresses have to be seperated by either a space or ;) then press Add to add
to
the
list. You can edit
the addresses directly as well as remove them.</p>
<div className="input-group">
<input type="text" className="form-control"
value={this.state.newEmailAddress}
onChange={this.handleAddNewEmail}
placeholder="Email addresses seperated by a space or a semicolon ; i.e. test1#test.se;test2#test.se"/>
<span className="input-group-btn">
<button type="button" onClick={this.handleAddNewEmailButton} className="btn btn-info btn-flat add-email">Add</button>
</span>
</div>
<br/>
{this.renderEmail()}
</div>
</form>
</div>
)
},
render()
{
var contentStyle = {
minHeight : '946px'
};
return (
<div className="content-wrapper" style={contentStyle}>
<section className="content-header">
<h1>
{this.data.emailGroup? this.data.emailGroup.name : 'hello'}
</h1>
<small> Created by: Christian Klinton</small>
<br/>
<small> Last updated by: Christian Klinton - 2015-11-12 08:10:11</small>
<ol className="breadcrumb">
<li><i className="fa fa-dashboard"></i> Home</li>
<li>Email groups</li>
<li className="active">{this.data.emailGroup? this.data.emailGroup.name : 'loading'}</li>
</ol>
</section>
<section className="content">
<div className="row">
<div className="col-md-6">
<div className="box box-primary">
<div className="box-header with-border">
<h3 className="box-title">Information</h3>
</div>
<form role="form">
<div className="box-body">
<div className="form-group">
<label htmlFor="inputName">Name</label>
<input type="email" className="form-control" id="name"
onChange={this.handleNameChange}
placeholder="Set the name of the email group" autoComplete="off"
value={this.state.name}/>
</div>
<div className="form-group">
<label>Description</label>
<textarea className="form-control" rows="3" id="description"
placeholder="Enter a description what and how the template is used..."
onChange={this.handleDesriptionChange}
value={this.state.description}
></textarea>
</div>
</div>
</form>
</div>
</div>
<div className="col-md-6">
{this.data.emailGroup? this.getContent() : <p>Loading</p> }
</div>
<div className="form-group">
<div className="col-sm-offset-8 col-sm-4">
<div className="pull-right">
<button className="btn btn-primary">Delete all</button>
<button className="btn btn-primary save">Save</button>
</div>
</div>
</div>
</div>
</section>
</div>
)
}
React requires you to have something unique for every element in the rendered array, it's called a key, and it's an attribute.
If you don't know what to assign to the key, just assign it the array's indexes:
this.props.doors.map((door, index) => (
<div key={index} className="door"></div>
));
Here's the same solution applied to your problem:
return this.data.emailGroup.emails.map((email, index) => {
return (
<div key={index} className="input-group">
<input type="text"
className="form-control"
onChange={self.handleEmailListChange.bind(this, index)} value={email}/>
</div>
);
});
Notice how I bound handleEmailListChange to receive the index of the modified email. If handleEmailListChange accepts an index, it can update the modified email within the state:
handleEmailListChange: function(index, event) {
var emails = this.state.emails.slice(); // Make a copy of the emails first.
emails[index] = event.target.value; // Update it with the modified email.
this.setState({emails: emails}); // Update the state.
}
I believe what you're looking for is something like this:
MyPage = React.createClass({
mixins: [ReactMeteorData],
getMeteorData() {
// ...
},
render() {
const emails = this.data.emailGroup.emails.map((email) => {
return (
<div key={email} className="input-group">
<input type="text" className="form-control"
onChange={this.handleEmailListChange} value={email} />
<div className="input-group-btn">
<button type="button"
className="btn btn-default remove-email"><span
className="glyphicon glyphicon-remove" /></button>
</div>
</div>
);
});
return <div>
{emails}
</div>
}
});
I changed self to this. Since you're using the ES6 arrow function, there's no need to assign self = this.
You should place your Array.map directly inside your render() function. Just take care that each array element is wrapped inside a parent element (<div> here) and must have a unique key={}
class ArrayMap extends React.Component{
//your functions
handleEmailChanged(key){
// Handle email
}
render(){
return(
<div>
{
this.data.emailGroup.emails.map((email) => {
<div key={email.key}>
<button onClick={this.handleEmailChanged.bind(this,email.key)}/>
</div>
});
}
</div>
);
}
}

Categories