Good afternoon,
I am having trouble changing the state of components which are siblings. Basically they look like this:
<Navigation>
<NavEndpt /> About <--- no
<NavEndpt /> Blog
<NavEndpt /> Projects
</Navigation>
Each <NavEndpt /> is a link that routes to a different 'page' or route on my website unless it is the first one listed, "About". About I want to be a drop down/lightbox feature something pretty to show off my CSS knowledge. So when one of the links is clicked I want it to go where I want; additionally, I'd like it to reflect which link is currently "active" (or not) by both changing it's state.active to true or false and adding an additional class active for CSS purposes. I want to new "active" class to only be present on a <NavEndpt /> that's state.active is true.
Yet everything I have tried so far hasn't worked and I've been at this for two days. I'd appreciate someone who is more experienced with React to show me how to accomplish this.
Here is what I am working with:
var MasterLayout = React.createClass({
mixins: [History],
render: function(){
var childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
doSomething: this.doSomething
})
);
return(
<div id="container">
<Navigation activeRoute={this.props.location.pathname} />
<div id="content">
{childrenWithProps}
</div>
</div>
)
}
});
var Navigation = React.createClass({
getInitialState: function(){
var endpoints = require("./data/naviEnd.js");
return {
endpoints: endpoints,
activeRoute: this.props.activeRoute
}
},
renderEndpoints: function(key){
var endpointDetails = this.state.endpoints[key];
return(
<NavEndpt id={endpointDetails.id} key={endpointDetails.title} url={endpointDetails.url} title={endpointDetails.title}/>
)
},
render: function(){
return(
<div id="navigation">
{Object.keys(this.state.endpoints).map(this.renderEndpoints)}
</div>
)
}
});
// Created child not a this.props.child of <Navigation /> component
// as pointed out by #BenHare
var NavEndpt = React.createClass({
handleClick: function(){
this.setState({
active: true
})
},
render: function(){
return (
<div onClick={this.handleClick} className="navLink" id={this.props.id}>
<Link id={this.props.id + "-link"} to={this.props.url}>{this.props.title}</Link>
</div>
)
}
})
Currently this only changes creates and set states for each <NavEndpt /> I tried to make this mess as clean as possible for Stack Overflow.
The best fix I have come up with so far uses a lot of DOM selection and hardcoded if/else statements. It also doesn't light up my "About" component because it doesn't have a url property. That's significant because I have the below solution tied up to the pathname of my entire layout component.
var MasterLayout = React.createClass({
mixins: [History],
render: function(){
var childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
doSomething: this.doSomething
})
);
return(
<div id="container">
<Navigation activeRoute={this.props.location.pathname} />
<div id="content">
{childrenWithProps}
</div>
</div>
)
}
});
// This is the parent component that sits on the side or the top depending on the
// broswer size, contains components NavEndpt
var Navigation = React.createClass({
getInitialState: function(){
var endpoints = require("./data/naviEnd.js");
return {
endpoints: endpoints,
activeRoute: this.props.activeRoute
}
},
// Always makes the website's initial view the home route
componentDidMount: function(){
var cover = document.getElementById("cover");
var projects = document.getElementById("projects");
var about = document.getElementById("about");
var active = this.props.activeRoute
this.setActive();
},
// resets the hard coded CSS class
resetClasses: function(){
var active = this.props.activeRoute
var cover = document.getElementById("cover");
var projects = document.getElementById("projects");
var about = document.getElementById("about");
cover.className = "navLink";
projects.className = "navLink";
about.className = "navLink";
},
// checks pathname of <MasterLayout/>
// also somehow makes it so a refresh does not
// return you to "/"
setActive: function(){
var active = this.props.activeRoute
var cover = document.getElementById("cover");
var projects = document.getElementById("projects");
var about = document.getElementById("about");
if (active === "/"){
cover.className += " active";
} else if (active === "/projects"){
projects.className += " active"
} else if (active === "/about"){
about.className += " active"
}
},
// listens for updates, resets active first and sets it
componentDidUpdate: function(){
this.resetClasses();
this.setActive();
},
renderEndpoints: function(key){
var endpointDetails = this.state.endpoints[key];
return(
<NavEndpt id={endpointDetails.id} key={endpointDetails.title} url={endpointDetails.url} title={endpointDetails.title}/>
)
},
render: function(){
return(
<div id="navigation">
{Object.keys(this.state.endpoints).map(this.renderEndpoints)}
</div>
)
}
});
var NavEndpt = React.createClass({
handleClick: function(){
this.setState({
active: true
})
},
render: function(){
return (
<div onClick={this.handleClick} className="navLink" id={this.props.id}>
<Link id={this.props.id + "-link"} to={this.props.url}>{this.props.title}</Link>
</div>
)
}
})
Related
I have a simple layout.
There is a <StateSelector> in <Navbar> clicking on that executes a method.
The value of innerHTML of that button in <StateSelector> is passed as an argument to a function that was passed to it as a prop. And the method present in parent changes the activeOption State to All, Offline and online depending on the button clicked.
Now, There is one more child to this parent called <TwitchList>. This <TwitchList>'s render method contains an array of 8 users names and 8 calls are made to twitch.tv to get data for those channels.
Note that I have not linked <StateSelector> just yet. It has no interaction to $.ajax(); in <TwitchList> except the fact that <TwitchList> and <StateSelector> belong to same parent.
Why does clicking on a element inside <StateSelector> generating ajax calls?
And clicking on it one time generates 8 calls which is equal to number of users in usersList[].
I have tried searching for this issue and I have tried to work my way around for about 4 days now and I just don't understand why it is happenning.
var Navbar = React.createClass({
render: function () {
return (
<div className="navbar">
<h1 className="header">TWITCH STREAMERS</h1>
<StateSelector changeActiveOption={this.props.changeActiveOption}/>
</div>
);
}
});
var StateSelector = React.createClass({
changeOption: function (e) {
this.props.changeActiveOption(e.target.innerHTML.toLowerCase());
},
render: function () {
return (
<div className="selectorList">
<div className="selector" onClick={this.changeOption}>ALL</div>
<div className="selector" onClick={this.changeOption}>ONLINE</div>
<div className="selector" onClick={this.changeOption}>OFFLINE</div>
</div>
);
}
});
var TwitchList = React.createClass({
render: function () {
var userslist = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var finalList = [];
function makeURL(user, type) {
return "https://api.twitch.tv/kraken/" + type + "/" + user;
}
userslist.forEach(function (user) {
$.ajax({
url: makeURL(user, "streams"),
dataType: 'jsonp',
success: function (data) {
function getID(data) {
if (data.stream) {
return data.stream._id;
} else {
return Math.random();
}
}
function getImage(data) {
if (!data.stream) {
return "https://dummyimage.com/50x50/ecf0e7/5c5457.jpg&text=0x3F";
}
else {
return data.stream.preview.medium;
}
}
console.log(data);
var id = getID(data);
var preview = getImage(data);
console.log(preview);
finalList.push(
<li className="twitchUser" key={id}>
<img src={preview} alt="preview"/>
</li>
)
},
fail: function (xhr, error, url) {
console.error(error + " " + xhr + " " + url);
}
});
});
return (
<div className= "twitchListWraper" >
<ul className="twitchList">
{finalList}
</ul>
</div>
)
}
});
var App = React.createClass({
getInitialState: function () {
return {
activeOption: "all"
};
},
changeActiveOption: function (option) {
this.setState({
activeOption: option
});
},
render: function () {
return (
<div className="app-root">
<Navbar changeActiveOption={this.changeActiveOption}/>
<TwitchList activeOption={this.state.activeOption}/>
</div>
);
}
});
ReactDOM.render(<App />, document.getElementById('root'));
JSBin: http://jsbin.com/sulihogegi/edit?html,css,js,console,output
Every time state changes on <App>, it re-renders. This includes re-rendering its children (on of which is <TwitchList>). Your ajax call is made in <TwitchList>'s render function, so every time state changes, it's going to be hitting that ajax code.
If you're wondering why the state's changing, it's because you have a function, changeActiveOption, that updates the <App>'s state being passed to <Navbar> which is then passes down to <StateSelector>.
The appropriate thing to do here is find a life cycle event in which to make the ajax call. I'd recommend componentWillMount and componentWillUpdate.
Take a look at lifecycle functions here.
you shouldn't write your ajax call to render function of TwitchList component instead you can write it to componentDidMount function
I'm trying to make a tag-suggest input field. I'm trying to understand why this code doesn't work, as it can be applied to any number of cases.
FYI: ReactComponent is just a helper class I implemented that contains few methods like _bind etc.
class TagSuggestInput extends ReactComponent {
constructor(){
super();
this._bind('handleSelectionClick', 'handleRemoveTag', 'addNewTag', 'render');
this.state = {
suggestedOptions: [],
tagListTo: []
};
}
addNewTag(selectedIndex){
var _this = this,
tag= _this.state.suggestedOptions[selectedIndex].tag,
tagList = _this.state.tagListTo;
if($.inArray(email, tagList) == -1){
_this.setState({tagListTO: tagList.push(tag)});
}
}
handleRemoveTag(tag){
var _this = this;
// Remove tag code goes here. This is not the problem part
}
handleSelectionClick(selectedIndex, e){
var _this = this;
_this.addNewTag(selectedIndex);
// other stuff here
}
render() {
var _this = this;
return (
<div className="tagitos">
{_this.state.tagListTo.map(function(item, index){
return (
<span key={index} >
<Tag data={item} onRemove={_this.handleRemoveTag.bind(_this)} />
</span>
);
})}
<input className="tag-input" ref="input"></input>
<ul>
{_this.state.suggestedOptions.map(function(item, index){
return (
<li key={index}
onClick={_this.handleSelectionClick.bind(_this, index)}
>
<OptionComponent data={item} index={index}/>
</li>
);
})}
</ul>
</div>
);
}
}
Child component
class Tag extends ReactComponent{
constructor(){
super();
this._bind('render', 'removeFromList');
}
removeFromList(tag){
var _this = this;
_this.props.onRemove(tag);
}
render(){
var _this = this;
return(
<span className="tag-element">
<div>{_this.props.data}</div>
<div onClick={_this.removeFromList(_this.props.data)} className="tag-closeButton">×</div>
</span>
);
}
}
I want to remove the tag by clicking on the tag X button, not on the tag itself, otherwise I could have just made the entire code in the parent scope like I did with options.
Workflow: Options are generated from back-end, as autocomplete, listed below the input field in the parent. When option is selected it generates a tag. So far so good!
BUT: the code for removing the tag is automatically called and tries to remove it. Since I've removed it the tag stays, but nothing happens on 'X' click. As if onCLick event is not bound.
Function removeFromList is not called, but it is called when component is added to the view. Why? How to prevent this? My guess is that by solving this I would solve the onClick problem also.
It doesn't work because you do not bind function to onclick. You only run it once on each render
You may write something like this
removeFromList(){
var _this = this;
var tag = _this.props.data;
_this.props.onRemove(tag);
}
...
<div onClick={_this.removeFromList}></div>
I've hit a wall as I start my adventure with React.js. I've got the UI of the following time tracking app working on several levels:
http://jsfiddle.net/technotarek/4n8n17tr/
What's working as hoped:
Filtering based on user input
Project clocks can be started and stopped independently
What's not working:
If you start one or more clocks and then try to filter, any clock that's not in the filter result set gets reset once it is re-displayed. (Just click the start on all clocks, then search for a project, then clear your search input.)
I assume this is happening because a setState is run onChange of the filter input, which is re-rendering everything and using the clock getInitialState values.
So, what's the correct way to preserve the 'state' of these clocks and the buttons when the filter re-renders the components? Should I not be storing the clock or the button 'states' as genuine React states? Do I need a function to explicitly save the clock values before the re-render?
I'm not asking for anyone to fix my code. Rather, I'm hoping for a pointer in where my understanding of React is failing.
To satisfy SO's code requirement, below is the component that contains each row in the time tracker. The clocks are started via toggleClock. IncrementClock writes the state that is getting cleared out by the search filter. Please see the complete code in the fiddle link above.
var LogRow = React.createClass({
getInitialState: function() {
return {
status: false,
seconds: 0
};
},
toggleButton: function(status) {
this.setState({
status: !this.state.status
});
this.toggleClock();
},
toggleClock: function() {
var interval = '';
if(this.state.status){
// if clock is running, pause it.
clearInterval(this.interval);
} else {
// otherwise, start it
this.interval = setInterval(this.incrementClock, 1000);
}
},
incrementClock: function() {
this.setState({ seconds: this.state.seconds+1 });
},
render: function() {
var clock = <LogClock seconds={this.state.seconds} />
return (
<div>
<div className="row" key={this.props.id}>
<div className="col-xs-7"><h4>{this.props.project.title}</h4></div>
<div className="col-xs-2 text-right">{clock}</div>
<div className="col-xs-3 text-right"><TriggerButton status={this.state.status} toggleButton={this.toggleButton} /></div>
</div>
<hr />
</div>
);
}
})
When you filter, you're removing LogRow components from the rendered output - when this happens, React unmounts the component and disposes of its state. When you subsequently change the filter and a row is once again displayed, you're getting an entirely new LogRow component, so getInitialState() is called again.
(You also have a leak here because you're not clearing the interval when these components unmount using the componentWillUnmount() lifecycle hook - those intervals are still running away the background)
To solve this, you could move the timer state and the methods which control and increment it up out of the LogRow component, so its job is just to display and control the current state but not to own it.
You're currently using the LogRow component to tie the state and behaviour of a project timer together. You could either move this state and behaviour management up to a parent component which will manage it the same way, or out into another object, e.g.:
function Project(props) {
this.id = props.id
this.title = props.title
this.ticking = false
this.seconds = 0
this._interval = null
}
Project.prototype.notifyChange = function() {
if (this.onChange) {
this.onChange()
}
}
Project.prototype.tick = function() {
this.seconds++
this.notifyChange()
}
Project.prototype.toggleClock = function() {
this.ticking = !this.ticking
if (this.ticking) {
this.startClock()
}
else {
this.stopClock()
}
this.notifyChange()
}
Project.prototype.startClock = function() {
if (this._interval == null) {
this._interval = setInterval(this.tick.bind(this), 1000)
}
}
Project.prototype.stopClock = function() {
if (this._interval != null) {
clearInterval(this._interval)
this._interval = null
}
}
Since the clearIntervals being used are an external source of change, you'd need to subscribe to them somehow, so I've implemented the ability to register a single onChange callback, which the LogRow component is doing when it mounts in the snippet below.
The working code snippet below does the most simple and direct thing possible to achieve this and as a result the solution has some discouraged practices (modifying props) and caveats (you can only have one "listener" on a Project) but it works. (This is generally my experience with React - it works first, then you make it "right" afterwards).
Next steps could be:
PROJECTS is effectively a singleton Store - you could make it an object which allows registration of listeners for changes to project state. You could then add an Action object to encapsulate triggering changes to project state so LogRow never touches its project prop directly, only reads from it and calls sideways to an Action to change it. (This is just indirection, but helps with thinking about data flow). See the Less Simple Communication example in the react-trainig repo for a worked example of this.
You could make LogRow completely dumb by listening for all project changes at a higher level and re-rendering everything on change. Passing individual project props to LowRow would then allow you to implement shouldComponentUpdate() so only rows which need to display a change actually re-render.
<meta charset="UTF-8">
<script src="http://fb.me/react-with-addons-0.12.2.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<div class="container">
<div class="row">
<div id="worklog" class="col-md-12">
</div>
</div>
</div>
<script type="text/jsx;harmony=true">void function() { "use strict";
/* Convert seconds input to hh:mm:ss */
Number.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
function Project(props) {
this.id = props.id
this.title = props.title
this.ticking = false
this.seconds = 0
this._interval = null
}
Project.prototype.notifyChange = function() {
if (typeof this.onChange == 'function') {
this.onChange()
}
}
Project.prototype.tick = function() {
this.seconds++
this.notifyChange()
}
Project.prototype.toggleClock = function() {
this.ticking = !this.ticking
if (this.ticking) {
this.startClock()
}
else {
this.stopClock()
}
this.notifyChange()
}
Project.prototype.startClock = function() {
if (this._interval == null) {
this._interval = setInterval(this.tick.bind(this), 1000)
}
}
Project.prototype.stopClock = function() {
if (this._interval != null) {
clearInterval(this._interval)
this._interval = null
}
}
var PROJECTS = [
new Project({id: "1", title: "Project ABC"}),
new Project({id: "2", title: "Project XYZ"}),
new Project({id: "3", title: "Project ACME"}),
new Project({id: "4", title: "Project BB"}),
new Project({id: "5", title: "Admin"})
];
var Worklog = React.createClass({
getInitialState: function() {
return {
filterText: '',
};
},
componentWillUnmount: function() {
this.props.projects.forEach(function(project) {
project.stopClock()
})
},
handleSearch: function(filterText) {
this.setState({
filterText: filterText,
});
},
render: function() {
var propsSearchBar = {
filterText: this.state.filterText,
onSearch: this.handleSearch
};
var propsLogTable = {
filterText: this.state.filterText,
projects: this.props.projects
}
return (
<div>
<h2>Worklog</h2>
<SearchBar {...propsSearchBar} />
<LogTable {...propsLogTable} />
</div>
);
}
});
var SearchBar = React.createClass({
handleSearch: function() {
this.props.onSearch(
this.refs.filterTextInput.getDOMNode().value
);
},
render: function() {
return (
<div className="form-group">
<input type="text" className="form-control" placeholder="Search for a project..." value={this.props.filterText} onChange={this.handleSearch} ref="filterTextInput" />
</div>
);
}
})
var LogTable = React.createClass({
render: function() {
var rows = [];
this.props.projects.forEach(function(project) {
if (project.title.toLowerCase().indexOf(this.props.filterText.toLowerCase()) === -1) {
return;
}
rows.push(<LogRow key={project.id} project={project} />);
}, this);
return (
<div>{rows}</div>
);
}
})
var LogRow = React.createClass({
componentDidMount: function() {
this.props.project.onChange = this.forceUpdate.bind(this)
},
componentWillUnmount: function() {
this.props.project.onChange = null
},
onToggle: function() {
this.props.project.toggleClock()
},
render: function() {
return <div>
<div className="row" key={this.props.id}>
<div className="col-xs-7">
<h4>{this.props.project.title}</h4>
</div>
<div className="col-xs-2 text-right">
<LogClock seconds={this.props.project.seconds}/>
</div>
<div className="col-xs-3 text-right">
<TriggerButton status={this.props.project.ticking} toggleButton={this.onToggle}/>
</div>
</div>
<hr />
</div>
}
})
var LogClock = React.createClass({
render: function() {
return (
<div>{this.props.seconds.toHHMMSS()}</div>
);
}
});
var TriggerButton = React.createClass({
render: function() {
var button;
button = this.props.status != false
? <button className="btn btn-warning" key={this.props.id} onClick={this.props.toggleButton}><i className="fa fa-pause"></i></button>
: <button className="btn btn-success" key={this.props.id} onClick={this.props.toggleButton}><i className="fa fa-play"></i></button>
return (
<div>
{button}
</div>
);
}
})
React.render(<Worklog projects={PROJECTS} />, document.getElementById("worklog"));
}()</script>
I am loading a series of sentences into an array Sentences in React. On my front end I have one "active" sentence and after user form input the next sentence in the loaded array should become "active" with a new CSS class attached to it.
How would I go about doing this? I understand SentenceList needs to keep track of the active_sentence and the Sentence needs to tell SentenceList has been updated, and when it does it should set the class "active" to the next sentence sequentially. But I'm not sure how to implement it.
SentenceList:
var SentenceList = React.createClass({
render: function() {
var sentences = [];
active_sentence = 0;
//loop through sentences and push each sentence into array
this.props.sentences.forEach(function(sentence) {
// increment an index variable here and put an if index === active_sentence statement?
//grabs #sentences from Rails
sentences.push(<Sentence key={sentence.id} details={sentence} />)
});
return (
<div>{sentences}</div>
)
}
});
Sentence:
var Sentence = React.createClass({
getInitialState: function() {
return {
//
}
},
addBlip: function(e) {
var blipBody = this.refs.newBlip.getDOMNode().value;
var sentenceId = this.props.details.id;
var thisSentenceComponent = this;
$.ajax({
url: '/sentences/' + sentenceId + '/blips',
type: 'POST',
dataType: 'json',
data: {blip: {body: blipBody}}
});
e.preventDefault();
},
render: function() {
//get user input and submit blip and make next sentence "active"
var phrase = this.props.details.body;
var phrase_display = phrase.split("*");
return (
<div className="blipForm">
{phrase_display[0]}
{this.props.details.index}
<form onSubmit={this.addBlip}>
<input
type="text"
ref="newBlip"
/>
</form>
{phrase_display[1]}
</div>
)
}
});
You can create a variable in state (activeKey in this example) to keep track of which sentence key is considered active, then a prop can be passed to Sentence telling it whether it is active. The function setActiveKey below can be used to update the active sentence when you load a new sentence :
var SentenceList = React.createClass({
getInitialState: function() {
return {
activeKey: false
};
},
setActiveKey(newActiveKey){
this.setState({activeKey: newActiveKey});
},
render: function() {
var sentences = [];
this.props.sentences.forEach(function(sentence) {
sentences.push(<Sentence isActive={this.state.activeKey === sentence.id} key={sentence.id} details={sentence} />)
}.bind(this));
return (
<div>{sentences}</div>
)}
});
Then within the render function of Sentence, you can the prop isActive, and if the value is true, you can render it with the active style:
render: function() {
var phrase = this.props.details.body
var phrase_display = phrase.split("*");
return (
<div className="blipForm" style={this.props.isActive ? styles.active : styles.inactive}>
{phrase_display[0]}
{this.props.details.index}
<form onSubmit={this.addBlip}>
<input type="text"
ref="newBlip" />
</form>
{phrase_display[1]}
</div>
)
}
And you can control your styles in a variable (styles here):
var styles={
active:{
//set active styles here
},
inactive:{
//set inactive styles here
}
};
I'm trying to dynamically generate alert components in React-Bootstrap at runtime by instantiating the components from Javascript classes. I'm doing this because there are lots of alerts to show and because Javascript classes are more succinct to create.
My attempts to do this are not working. I'm not sure whether the problem generally applies to React or just to React-Bootstrap. However, the error occurs in react.js, which throws the following:
TypeError: undefined is not a function
The throw occurs in the alert.getComponent() call in the following JSX file:
/** #jsx React.DOM */
var Alert = ReactBootstrap.Alert;
var AlertDismissible = React.createClass({
getInitialState: function() {
return {
isVisible: true
};
},
render: function() {
if(!this.state.isVisible)
return null;
var message = this.props.message;
if(this.props.code !== null)
message = message +'(Code '+ this.props.code +')';
return (
<Alert bsStyle={this.props.level} onDismiss={this.dismissAlert}>
<p>{message}</p>
</Alert>
);
},
dismissAlert: function() {
this.setState({isVisible: false});
}
});
function AlertNotice(level, message, code) {
this.level = level;
this.message = message;
this.code = code || null;
}
AlertNotice.prototype.getComponent = function() {
// What should go here? Using React.createClass() doesn't help
return (
<AlertDismissible level={this.level} message={this.message}
code={this.code} />
);
};
function SuccessAlert(message) {
AlertNotice.call(this, 'success', message);
}
SuccessAlert.prototype = Object.create(AlertNotice);
SuccessAlert.prototype.constructor = SuccessAlert;
/* ...more kinds of alerts... */
function ErrorAlert(message, code) {
AlertNotice.call(this, 'danger', message, code);
}
ErrorAlert.prototype = Object.create(AlertNotice);
ErrorAlert.prototype.constructor = ErrorAlert;
var SomethingWithAlerts = React.createClass({
render: function() {
var alerts = [
new ErrorAlert("Goof #1", 123),
new ErrorAlert("Goof #2", 321)
].map(function(alert) {
// react.js throws "TypeError: undefined is not a function"
return alert.getComponent();
});
return (
<div>{alerts}</div>
);
}
});
var TestComponent = (
<div>
<SomethingWithAlerts />
</div>
);
React.renderComponent(
TestComponent,
document.getElementById('content')
);
The Alert component comes from the React-Bootstrap library. The div components seem extraneous but I found them necessary to satisfy the react framework. In reality, I'll be storing the AlertNotice instances in react state and then generating react nodes from them.
What is the proper way to go about this?
Here's a hint. If I replace return alert.getComponent(); with the following hardcoded alert, the AlertDismissible components render without error (in duplicate) but I get a warning:
return (
<AlertDismissible level="danger" message="Goof" code="777" />
);
The following is the warning message I get with the above replacement, including a link that explains I should set key= to a unique for each alert:
Each child in an array should have a unique "key" prop. Check the render method
of SpecimenSetManager. See http://fb.me/react-warning-keys for more information.
However, if I simply replace the code inside of AlertNotice.prototype.getComponent with the above hardcoded alert, I get the same TypeError message as before.
For completeness, here is my HTML source. This is react and react-boostrap v0.11.1
<html>
<head>
<script src="lib/react.js"></script>
<script src="lib/react-bootstrap.js"></script>
<script src="lib/JSXTransformer.js"></script>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div id="content"></div>
<script src="components.js" type="text/jsx"></script>
</body>
</html>
I solved the problem. The solution was to create a special react component that represents a set of alerts. Apparently it is only possible to reference automatic or object variables in component parameters from within the React.createClass() definition. Perhaps this is a syntactic constraint of JSX rather than a logical constraint of react.
I don't understand why this solution works. I would like to understand so that I don't have to deal with similar problems again in the future. If you can explain the general principle I'm violating and the general principle that should be followed instead -- something more insightful than what I've stated here -- then I'll mark your response as the "answer" to this question. I'd like to know how much flexibility I really have.
Here's the code that works, including a new AlertSet component:
/** #jsx React.DOM */
function AlertNotice(level, message, code) {
this.level = level;
this.message = message;
this.code = code || null;
}
function SuccessAlert(message) {
AlertNotice.call(this, 'success', message);
}
SuccessAlert.prototype = Object.create(AlertNotice);
SuccessAlert.prototype.constructor = SuccessAlert;
/* ...more kinds of alerts... */
function ErrorAlert(message, code) {
AlertNotice.call(this, 'danger', message, code);
}
ErrorAlert.prototype = Object.create(AlertNotice);
ErrorAlert.prototype.constructor = ErrorAlert;
var Alert = ReactBootstrap.Alert;
var AlertDismissible = React.createClass({
getInitialState: function() {
return {
isVisible: true
};
},
render: function() {
if(!this.state.isVisible)
return null;
var message = this.props.message;
if(this.props.code !== null)
message = message +'(Code '+ this.props.code +')';
return (
<Alert bsStyle={this.props.level} onDismiss={this.dismissAlert}>
<p>{message}</p>
</Alert>
);
},
dismissAlert: function() {
this.setState({isVisible: false});
}
});
var AlertSet = React.createClass({
render: function() {
var alerts = this.props.alerts.map(function(alert, i) {
return (
<AlertDismissible key={"alert-"+i} level={alert.level}
message={alert.message} code={alert.code} />
);
});
// component must be a single node, so wrap in a div
return (
<div>{alerts}</div>
);
}
});
var SomethingWithAlerts = React.createClass({
render: function() {
var alerts = [
new ErrorAlert("Goof #1", 123),
new ErrorAlert("Goof #2", 321)
];
return (
<AlertSet alerts={alerts} />
);
}
});
// TestComponent returns a single node, so doesn't need a div
var TestComponent = (
<SomethingWithAlerts />
);
React.renderComponent(
TestComponent,
document.getElementById('content')
);