React not rendering class - javascript

I believe I have a syntax area somewhere, but I can't figure it out.
Note: I am new to React and I am using Sharepoint to develop.
My Js file:
var newt = React.createClass({
getInitialState: function () {
return {
greeting: 'This is really',
thing: 'code stuff'
};
},
render: function () {
return (
<div id="react-newt">
{this.state.greeting} {this.state.thing}!
</div>
);
}
});
$(function () {
if (document.getElementById('newt')) {
React.render(
<newt />,
document.getElementById('newt')
);
console.log('newt');
}
});
And my HTML file:
<div id="newt"></div>
I inspect the console and I see this:

You have to use a capitalised name for the component. JSX treats lowercase as a built-in HTML component. See User-Defined Components Must Be Capitalized for more details.
var Newt = React.createClass({
getInitialState: function () {
return {
greeting: 'This is really',
thing: 'code stuff'
};
},
render: function () {
return (
<div id="react-newt">
{this.state.greeting} {this.state.thing}!
</div>
);
}
});
$(function () {
if (document.getElementById('newt')) {
React.render(
<Newt />,
document.getElementById('newt')
);
console.log('newt');
}
});

Related

React: Search Results not being displayed?

So I am learning react.js, and I am developing a quick search engine using the GitHub API of users.
The API side of the project works fine (I have tested by manually entering names into the area)
Its the search build in react that is not working.
(FYI: I am using Plunker which has react support)
script.jsx
var Card = React.createClass({
getInitialState: function(){
return{};
},
componentDidMount: function(){
var component = this;
$.get("https://api.github.com/users/" + this.props.login, function(data){
component.setState(data);
});
},
render: function(){
return(
<div>
<img src={this.state.avatar_url} width="100"/>
<h3>{this.state.name}</h3>
<hr/>
</div>
);
}
});
var Form = React.createClass({
handleSubmit: function(e){
e.preventDefault();
var loginInput = React.findDOMNode(this.refs.login);
this.props.addCard(loginInput.value);
loginInput.value = '';
},
render: function(){
return(
<form onSubmit={this.handleSubmit}>
<input placeholder="Enter Github Name" ref="login"/>
<button>Search</button>
</form>
);
}
});
var Main = React.createClass({
getInitialState: function(){
return {logins: []};
},
addCard: function(loginToAdd){
this.setState({logins: this.state.logins.concat(loginToAdd)});
},
render: function() {
var cards = this.state.logins.map(function(login){
return (<Card login={login} />);
});
return(
<div>
<Form addCard={this.addCard} />
{cards}
</div>
)
}
});
ReactDOM.render(<Main />, document.getElementById("root"));
The problem was (if you check console), that you had a duplicate script tag in the <head> which you didn't need. And also, you were doing React.findDOMNode instead of ReactDOM.findDOMNode
Line 25 of your JSX file:
var loginInput = ReactDOM.findDOMNode(this.refs.login);
That said, you don't need to do ReactDOM.findDOMNode. You can just use this.refs.login

Updating State, but not re-rendering in ReactJS?

I am very new to React and am just getting my feet wet. I'm having a hard time understand why this isn't re-rending the List. Here is my code:
app.jsx
var Hello = React.createClass({
getInitialState: function() {
return {
links: ['test ']
}
},
render: function() {
return <div className = "row">
<Submission linkStore = {this.state.links}/>
<List links = {this.state.links} />
</div>
}
});
var element = React.createElement(Hello, {});
ReactDOM.render(element, document.querySelector('.container'));
In my submission.jsx I have this function to push info into the links array
handleSubmitClick: function() {
this.props.linkStore.push(this.props.text)
this.setState({text: ''})
console.log(this.props.linkStore)
}
My list.jsx looks like this
module.exports = React.createClass({
getInitialState: function() {
return {
links: this.props.links
}
},
render: function() {
return <div>
{this.props.links}
</div>
}
});
Everything works as intended and I can get the test to show appropriately.
I am aware that this isn't going to show up as an actual list and that I should create a list component to show the items in list form. I'm just trying to run tests along the way to see how everything works.
Use parent state instead of child props.
try this
app.jsx
var Hello = React.createClass({
getInitialState: function() {
return {
links: ['test ']
}
},
handleListSubmitClick: function(params) {
this.setState({links:params});
},
render: function() {
return <div className = "row">
<Submission linkStore = {this.state.links} handleListSubmitClick={this.handleListSubmitClick}/>
<List links = {this.state.links} />
</div>
}
});
submission.jsx
handleSubmitClick: function() {
var linkStore = this.props.linkStore;
linkStore.push(this.props.text)
this.setState({text: ''})
this.props.handleListSubmitClick(linkStore);
}
but I don't understand this.props.text. input's value using this.refs.ref
list.jsx
module.exports = React.createClass({
getInitialState: function() {
return {
links: this.props.links
}
},
render: function() {
return <div>
{this.props.links}
</div>
}
});

call function inside of className react.js

How do I call the function for getClass for the className inside this example? The way I have it written out does not seem to call getClass.
var CreateList = React.createClass({
getClass: function() {
//some code to return className
},
render: function() {
return(
<div className{this.getClass}>Example</div>
);
}
});
You're referencing the instance of the getClass() function as opposed to calling the function. Try tweaking it like so:
render: function() {
return(
<div className={this.getClass()}>Example</div>
);
}
className{this.getClass} won't compile. Try this:
var CreateList = React.createClass({
getClass: function() {
//some code to return className
},
render: function() {
return(
<div className={this.getClass()}>Example</div>
);
}
});
If you want the div to have a class name that starts with 'className', then prepend that string to the result of the call: className={'className' + this.getClass()}.
functional component
const statusColor = () => {
return 'red';
};
<span className={statusColor()}>your text</span>

How to call another component from onClick function in ReactJS

I am learning Reactjs. I have implemented one sample react app with rails. I have search a lots to find the solution but I didn't find any. I wanted to call another component from onClick function. But nothing happen. Is that possible what I try to achieve? If yes, then please point me where I do mistake and If not, then which way I can implement. Here is my code:
var Comment = React.createClass({
render: function () {
return (
<div id={"comment_"+ this.props.id }>
<h4>{ this.props.author } said:</h4>
<p>{ this.props.desc }</p>
<a href='' onClick={this.handleDelete}>Delete</a> | #this is for delete which works great
<a href='' onClick={this.handleEdit}>Edit</a>
# If I put here then it works fine <UpdateComments comments={ this.props} /> but I don't want it here
</div>
)
},
handleDelete: function(event) {
$.ajax({
url: '/comments/'+ this.props.id,
type: "DELETE",
dataType: "json",
success: function (data) {
this.setState({ comments: data });
}.bind(this)
});
},
handleEdit: function(event) {
var Temp = React.createClass({
render: function(event){
return(<div>
<UpdateComments comments={ this.props} /> #here I want to call UpdateComments component
</div>
)
}
});
}
});
Update:
If I try below trick then it call the component but reload the page and again disappear called component :(
handleEdit: function() {
React.render(<UpdateComments comments={ this.props} /> , document.getElementById('comment_'+ this.props.id));
}
any other detail if you required then feel free to ask. Thanks in advance. :)
Maybe this fiddle could point you in right way
var Hello = React.createClass({
render: function() {
return <div>Hello {this.props.name}
<First1/>
<First2/>
</div>;
}
});
var First1 = React.createClass({
myClick: function(){
alert('Show 1');
changeFirst();
},
render: function() {
return <a onClick={this.myClick}> Saludo</a>;
}
});
var First2 = React.createClass({
getInitialState: function(){
return {myState: ''};
},
componentDidMount: function() {
var me = this;
window.changeFirst = function() {
me.setState({'myState': 'Hey!!!'})
}
},
componentWillUnmount: function() {
window.changeFirst = null;
},
render: function() {
return <span> Saludo {this.state.myState}</span>;
}
});
React.render(<Hello name="World" />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Basically I use those links:
communicate between components
dom event listeners
It hopes this helps.
Also, you could use the container component and use it like a bridge between both components.

Search in Backbone Collections, Updating UI with React

I'm spending time on something probably simple:
I'd like to implement a search bar, ideally updating the list of item as-you-type. My small app uses React and Backbone (for models and collections).
Displaying the list isn't too hard, it all works perfectly doing this (the mixin i'm using basically allows easy collections retrieval):
var List = React.createClass ({
mixins: [Backbone.React.Component.mixin],
searchFilter: function () {
//some filtering code here, not sure how (filter method is only for arrays...)
}
}
getInitialState: function () {
initialState = this.getCollection().map(function(model) {
return {
id: model.cid,
name: model.get('name'),
description: model.get('description')
}
});
return {
init: initialState,
items : []
}
},
componentWillMount: function () {
this.setState({items: this.state.init})
},
render: function(){
var list = this.state.items.map(function(obj){
return (
<div key={obj.id}>
<h2>{obj.name}</h2>
<p>{obj.description}</p>
</div>
)
});
return (
<div className='list'>
{list}
</div>
)
}
});
Now i've tried with no success to first translate the backbone collection into "state" with the getInitialState method, my idea was to proxy through a copy of the collection, which then could hold the search results. I'm not showing here my attemps for the sake of clarity(edit: yes i am), could someone guide me to the right approach? Thanks in advance.
There are many ways to accomplish this, but the simplest (in my opinion) is to store your search criteria in the List component's state and use it to filter which items from your collection get displayed. You can use a Backbone collection's built in filter method to do this.
var List = React.createClass ({
mixins: [Backbone.React.Component.mixin],
getInitialState: function () {
return {
nameFilter: ''
};
},
updateSearch: function (event) {
this.setState({
nameFilter: event.target.value
});
},
filterItems: function (item) {
// if we have no filter, pass through
if (!this.state.nameFilter) return true;
return item.name.toLowerCase().indexOf(this.state.nameFilter) > -1;
},
render: function(){
var list = this.props.collection
.filter(this.filterItems.bind(this))
.map(function(obj){
return (
<div key={obj.id}>
<h2>{obj.name}</h2>
</div>
)
});
return (
<div className='list'>
{list}
<input onChange={this.updateSearch} type="text" value={this.state.nameFilter}/>
</div>
)
}
});
var collection = new Backbone.Collection([
{
name: 'Bob'
},
{
name: 'Bill'
},
{
name: 'James'
}
]);
React.render(<List collection={collection}/>, document.body);
jsbin
The search criteria could easily be passed down from a parent component as a prop, so the search input does not have to live inside your List component.
Eventually I also found a different solution (below), but it involves copying the entire collection into state, which is probably not such a good idea...
var List = React.createClass ({
mixins: [Backbone.React.Component.mixin],
searchFilter: function () {
var updatedlist = this.state.init;
var searchText = this.refs.searchbar.getDOMNode().value
updatedlist = updatedlist.filter(function (item) {
return item.name.toLowerCase().search(
searchText.toLowerCase()) !== -1
});
this.setState({items: updatedlist})
}
},
getInitialState: function () {
initialState = this.getCollection().map(function(model) {
return {
id: model.cid,
name: model.get('name'),
description: model.get('description')
}
});
return {
init: initialState,
items : []
}
},
componentWillMount: function () {
this.setState({items: this.state.init})
},
render: function(){
var list = this.state.items.map(function(obj){
return (
<div key={obj.id}>
<h2>{obj.name}</h2>
<p>{obj.description}</p>
</div>
)
});
return (
<div className='list'>
<input ref='searchbar' type="text" placeholder="Search" onChange={this.searchFilter}/>
{list}
</div>
)
}
});

Categories

Resources