React JS onClick event handler - javascript

I have
var TestApp = React.createClass({
getComponent: function(){
console.log(this.props);
},
render: function(){
return(
<div>
<ul>
<li onClick={this.getComponent}>Component 1</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp />, document.body);
I want to color the background of the clicked list element. How can I do this in React ?
Something like
$('li').on('click', function(){
$(this).css({'background-color': '#ccc'});
});

Why not:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render:
onItemClick: function (event) {
this.setState({ selectedItem: event.currentTarget.dataset.id });
//where 'id' = whatever suffix you give the data-* li attribute
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
</ul>
</div>
);
},
You'd want to put those <li>s into a loop, and you need to make the li.on and li.off styles set your background-color.

Two ways I can think of are
var TestApp = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<li onClick={this.getComponent.bind(this, 1)}>Component 1</li>
<li onClick={this.getComponent.bind(this, 2)}>Component 2</li>
<li onClick={this.getComponent.bind(this, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));
This is my personal favorite.
var ListItem = React.createClass({
getInitialState: function() {
return {
isSelected: false
};
},
handleClick: function() {
this.setState({
isSelected: true
})
},
render: function() {
var isSelected = this.state.isSelected;
var style = {
'background-color': ''
};
if (isSelected) {
style = {
'background-color': '#ccc'
};
}
return (
<li onClick={this.handleClick} style={style}>{this.props.content}</li>
);
}
});
var TestApp2 = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<ListItem content="Component 1" />
<ListItem content="Component 2" />
<ListItem content="Component 3" />
</ul>
</div>
);
}
});
React.renderComponent(<TestApp2 /> , document.getElementById('soln2'));
Here is a DEMO
I hope this helps.

Here is how you define a react onClick event handler, which was answering the question title... using es6 syntax
import React, { Component } from 'react';
export default class Test extends Component {
handleClick(e) {
e.preventDefault()
console.log(e.target)
}
render() {
return (
<a href='#' onClick={e => this.handleClick(e)}>click me</a>
)
}
}

Use ECMA2015. Arrow functions make "this" a lot more intuitive.
import React from 'react';
class TestApp extends React.Component {
getComponent(e, index) {
$(e.target).css({
'background-color': '#ccc'
});
}
render() {
return (
<div>
<ul>
<li onClick={(e) => this.getComponent(e, 1)}>Component 1</li>
<li onClick={(e) => this.getComponent(e, 2)}>Component 2</li>
<li onClick={(e) => this.getComponent(e, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));`

If you're using ES6, here's some simple example code:
import React from 'wherever_react_is';
class TestApp extends React.Component {
getComponent(event) {
console.log('li item clicked!');
event.currentTarget.style.backgroundColor = '#ccc';
}
render() {
return(
<div>
<ul>
<li onClick={this.getComponent.bind(this)}>Component 1</li>
</ul>
</div>
);
}
}
export default TestApp;
In ES6 class bodies, functions no longer require the 'function' keyword and they don't need to be separated by commas. You can also use the => syntax as well if you wish.
Here's an example with dynamically created elements:
import React from 'wherever_react_is';
class TestApp extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{name: 'Name 1', id: 123},
{name: 'Name 2', id: 456}
]
}
}
getComponent(event) {
console.log('li item clicked!');
event.currentTarget.style.backgroundColor = '#ccc';
}
render() {
<div>
<ul>
{this.state.data.map(d => {
return(
<li key={d.id} onClick={this.getComponent.bind(this)}>{d.name}</li>
)}
)}
</ul>
</div>
);
}
}
export default TestApp;
Note that each dynamically created element should have a unique reference 'key'.
Furthermore, if you would like to pass the actual data object (rather than the event) into your onClick function, you will need to pass that into your bind. For example:
New onClick function:
getComponent(object) {
console.log(object.name);
}
Passing in the data object:
{this.state.data.map(d => {
return(
<li key={d.id} onClick={this.getComponent.bind(this, d)}>{d.name}</li>
)}
)}

Handling events with React elements is very similar to handling events
on DOM elements. There are some syntactic differences:
React events are named using camelCase, rather than lowercase.
With JSX you pass a function as the event handler, rather than a string.
So as mentioned in React documentation, they quite similar to normal HTML when it comes to Event Handling, but event names in React using camelcase, because they are not really HTML, they are JavaScript, also, you pass the function while we passing function call in a string format for HTML, they are different, but the concepts are pretty similar...
Look at the example below, pay attention to the way event get passed to the function:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}

import React from 'react';
class MyComponent extends React.Component {
getComponent(event) {
event.target.style.backgroundColor = '#ccc';
// or you can write
//arguments[0].target.style.backgroundColor = '#ccc';
}
render() {
return(
<div>
<ul>
<li onClick={this.getComponent.bind(this)}>Component 1</li>
</ul>
</div>
);
}
}
export { MyComponent }; // use this to be possible in future imports with {} like: import {MyComponent} from './MyComponent'
export default MyComponent;

class FrontendSkillList extends React.Component {
constructor() {
super();
this.state = { selectedSkill: {} };
}
render() {
return (
<ul>
{this.props.skills.map((skill, i) => (
<li
className={
this.state.selectedSkill.id === skill.id ? "selected" : ""
}
onClick={this.selectSkill.bind(this, skill)}
style={{ cursor: "pointer" }}
key={skill.id}
>
{skill.name}
</li>
))}
</ul>
);
}
selectSkill(selected) {
if (selected.id !== this.state.selectedSkill.id) {
this.setState({ selectedSkill: selected });
} else {
this.setState({ selectedSkill: {} });
}
}
}
const data = [
{ id: "1", name: "HTML5" },
{ id: "2", name: "CSS3" },
{ id: "3", name: "ES6 & ES7" }
];
const element = (
<div>
<h1>Frontend Skill List</h1>
<FrontendSkillList skills={data} />
</div>
);
ReactDOM.render(element, document.getElementById("root"));
.selected {
background-color: rgba(217, 83, 79, 0.8);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
#user544079 Hope this demo can help :) I recommend changing background color by toggling classname.

import React from 'react';
class MyComponent extends React.Component {
getComponent(event) {
event.target.style.backgroundColor = '#ccc';
// or you can write
//arguments[0].target.style.backgroundColor = '#ccc';
}
render() {
return(
<div>
<ul>
<li onClick={this.getComponent.bind(this)}>Component 1</li>
</ul>
</div>
);
}
}
export { MyComponent }; // use this to be possible in future imports with {} like: import {MyComponent} from './MyComponent'
export default MyComponent;

You can make use of the React.createClone method. Create your element, than create a clone of it. During the clone's creation, you can inject props. Inject an onClick : method prop like this
{ onClick : () => this.changeColor(originalElement, index) }
the changeColor method will set the state with the duplicate, allowing you sto set the color in the process.
render()
{
return(
<ul>
{this.state.items.map((val, ind) => {
let item = <li key={ind}>{val}</li>;
let props = {
onClick: () => this.Click(item, ind),
key : ind,
ind
}
let clone = React.cloneElement(item, props, [val]);
return clone;
})}
</ul>
)
}

This is a non-standard (but not so uncommon) React pattern that doesn't use JSX, instead putting everything inline. Also, it's Coffeescript.
The 'React-way' to do this would be with the component's own state:
(c = console.log.bind console)
mock_items: [
{
name: 'item_a'
uid: shortid()
}
{
name: 'item_b'
uid: shortid()
}
{
name: 'item_c'
uid: shortid()
}
]
getInitialState: ->
lighted_item: null
render: ->
div null,
ul null,
for item, idx in #mock_items
uid = item.uid
li
key: uid
onClick: do (idx, uid) =>
(e) =>
# justf to illustrate these are bound in closure by the do lambda,
c idx
c uid
#setState
lighted_item: uid
style:
cursor: 'pointer'
background: do (uid) =>
c #state.lighted_item
c 'and uid', uid
if #state.lighted_item is uid then 'magenta' else 'chartreuse'
# background: 'chartreuse'
item.name
This example works -- I tested it locally.
You can check out this example code exactly at my github.
Originally the env was only local for my own whiteboard r&d purposes but I posted it to Github for this. It may get written over at some point but you can check out the commit from Sept 8, 2016 to see this.
More generally, if you want to see how this CS/no-JSX pattern for React works, check out some recent work here. It's possible I will have time to fully implement a POC for this app idea, the stack for which includes NodeJS, Primus, Redis, & React.

Related

Show/Hide Component in React

I am a beginner in the React and I am trying to make a sidebar with a navigation menu. When user click on the li tag with className "frist", the component FrstComponent opens, when user click on the li tag with className "second" SecondComponent opens etc. Like bootstrap tabs.
This is my code
class Navigation extends React.Component {
constructor(props) {
super(props)
this.state = {
isActive: "first"
}
this.handleClickChange =this.handleClickChange.bind(this)
}
handleClickChange(){
this.setState={
isActive: !this.state.isActive
}
}
render() {
const {active} = this.state.isActive
if(active === 'first'){
return <FristComponent/>
}
if(active === 'second'){
return <SecondComponent/>
}
return (
<div>
<ul>
<li
className="first"
onClick={this.handleClickChange}
>
FIRST
</li>
<li
className="second"
onClick={this.handleClickChange}
>
SECOND
</li>
<li className="third">THIRD</li>
<li className="fourth">FOURTH</li>
<li className="fifth">FIFTH</li>
</ul>
</div>
)
}
}
React.render(<Navigation />, document.getElementById('app'));
i'm trying to help you, but your code need more refactoring :)
import React from "react"
import ReactDOM from "react-dom";
class Navigation extends React.Component {
state = {
active: "first"
}
handleClickChange = e => {
const { className } = e.target
this.setState({ active: className})
}
render() {
const { active } = this.state
return (
<div>
{active === 'first' && <div>First Component</div>}
{active === 'second' && <div>Second Component</div>}
<ul>
<li className="first"
onClick={this.handleClickChange}
>
FIRST
</li>
<li
className="second"
onClick={this.handleClickChange}
>
SECOND
</li>
<li className="third">THIRD</li>
<li className="fourth">FOURTH</li>
<li className="fifth">FIFTH</li>
</ul>
</div>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Navigation />, rootElement);
You need to pass on className to state and check this variable when you rendering. If you have a questions by this code, you can ask :)

Change the style of the react component based on its props

I have a Header.js:
const Header = () => {
return (
<header className="header">
<Logo/>
<HeaderMenu target="home-link"/>
</header>);
}
and a HeaderMenu.js:
class HeaderMenu extends React.Component {
render() {
return(
<nav className="header-menu">
<a id="home-link">Home</a>
<a id="project-link">Projects</a>
<a id="blog-link">Blog</a>
<a id="about-me-link">About Me</a>
</nav>
);
}
}
How can I change an a elements style based on target props?
Example: if target="home-link", then an a element with id="home-link" has its text underlined and another a element doesn't.
You can do this by applying a class to any element that you want to have styled differently. In your example of giving a different style to the link for the current page, you can iterate over your links and give an "active" class to the link whose id matches the target.
For Example:
class HeaderMenu extends React.Component {
render() {
const { target } = this.props;
const linkData = [
{id: "home-link", title: "Home"},
{id: "project-link", title: "Projects"},
{id: "blog-link", title: "Blog"},
{id: "about-me-link", title: "About Me"},
];
const linkElements = linkNames.map(e => (
<a id={ e.id } className={ e.id === target ? "active" : "" }>{ e.title }</a>
));
return(
<nav className="header-menu">
{ linkElements }
</nav>
);
}
}
However if you use React Router (which you may want to do so the page doesn't refresh when a link is clicked) the <NavLink> component takes an activeClassName prop, which applies the given className any time the current location (url) matches the NavLink's to prop (which is analogous to the a tag's href).
Save menu data into an variable.
Use map to add a tag
Set an className = 'active' on the a where target is matched.
then write css to add underline.
HeaderMenu.js
class HeaderMenu extends React.Component {
constructor(props) {
super(props);
this.menus = [
{ id: 'home-link', name: 'Home' },
{ id: 'project-link', name: 'Projests' },
// ...
];
}
render() {
return(
<nav className="header-menu">
{
this.menus.map(menu => (<a id={menu.id} className={this.props.target === menu.id ? 'active' : ''}>{menu.name}</a>))
}
</nav>
);
}
}
css:
.active {
// text style when active
}

ReactJS. calling a function from an outside variable

I'm new to ReactJS and trying to make a small web application.
I have a list of items to put in a sidebar, and I want each item to give back a status tu the sidebar when clicked (so that I can style the active link accordingly).
import React, {Component} from 'react';
import SideBarItem from "./SideBarItem";
const items = {
'DASHBOARD' : 'home',
'Utenti': 'user',
'Corsi' : 'education',
'Logistica' : 'check',
'Comunicazioni': 'bullhorn'
};
const listItems = Object.entries(items).map(([key,value])=>{
return <SideBarItem
onClick={this.changeState(key)} active={this.state.active == key ? 'active' : ''}
title={key}
glyph={'glyphicon glyphicon-' + value.toString()}/>
});
class SideBar extends Component {
constructor(props) {
super(props);
this.state = {active: 'DASHBOARD'};
}
changeState (row) {
this.setState({
active: row
});
}
render() {
return (
<div id = "sidebar" className="col-sm-3 col-md-2 sidebar paper-depth-1">
<ul className = 'nav nav-sidebar'>
{listItems}
</ul>
</div>
);
}
}
export default SideBar;
But this code is returnig the following error:
TypeError: _this.changeState is not a function
I understand that there's something wrong in calling a component function from an outside variable, but I don't get how can I make this work in any other way.
If you create the list of items in render(), the this scope will be the component instance, as you need it to be.
class SideBar extends Component {
constructor(props) {
super(props);
this.state = {active: 'DASHBOARD'};
}
changeState(row) {
this.setState({
active: row
});
}
render() {
return (
<div id="sidebar" className="col-sm-3 col-md-2 sidebar paper-depth-1">
<ul className="nav nav-sidebar">
{Object.entries(items).map(([key,value]) =>
<SideBarItem
onClick={() => this.changeState(key)}
active={this.state.active == key ? 'active' : ''}
title={key}
glyph={'glyphicon glyphicon-' + value.toString()}
/>
)}
</ul>
</div>
);
}
}

Show/Hide (sub) list items with React JS

In a React JS component I am rendering a list of items (Recipes), using JS map function from an array, passed in from a App parent component. Each item has a sub list (Ingredients), again rendered using map function.
What I want is to show/hide the sub list of Ingredients when you click on the Recipe title. I use a onClick function on the title that sets the CSS to display none or block, but I get the following error:
Uncaught TypeError: Cannot read property 'openRecipe' of undefined
Here is my code:
var App = React.createClass({
getInitialState(){
return{
showModal:false,
recipeKeys: [ ],
recipes: [ ]
}
},
addRecipeKey: function(recipe){
var allKeys = this.state.recipeKeys.slice();
var allRecipes = this.state.recipes.slice();
allKeys.push(recipe.name);
allRecipes.push(recipe);
localStorage.setObj("recipeKeys", allKeys);
this.setState({recipeKeys: allKeys, recipes: allRecipes}, function(){
console.log(this.state);
});
},
componentDidMount: function(){
var dummyRecipes = [
{
"name": "Pizza",
"ingredients": ["Dough", "Tomato", "Cheese"]
},
{
"name": "Sushi",
"ingredients": ["Rice", "Seaweed", "Tuna"]
}
]
if(localStorage.getItem("recipeKeys") === null){
localStorage.setObj("recipeKeys", ["Pizza", "Sushi"]);
dummyRecipes.forEach(function(item){
localStorage.setObj(item.name, item);
});
this.setState({recipeKeys: ["Pizza", "Sushi"], recipes: dummyRecipes}, function(){
console.log(this.state);
});
} else {
var recipeKeys = localStorage.getObj("recipeKeys");
var recipes = [];
recipeKeys.forEach(function(item){
var recipeObject = localStorage.getObj(item);
recipes.push(recipeObject);
});
this.setState({recipeKeys: recipeKeys, recipes: recipes}, function(){
console.log(this.state);
});
}
},
open: function(){
this.setState({showModal:true});
},
close: function(){
this.setState({showModal:false});
},
render: function(){
return(
<div className="container">
<h1>Recipe Box</h1>
<RecipeList recipes = {this.state.recipes} />
<AddRecipeButton openModal = {this.open}/>
<AddRecipe closeModal = {this.close} showModal={this.state.showModal} addRecipeKey = {this.addRecipeKey}/>
</div>
)
}
});
var RecipeList = React.createClass({
openRecipe: function(item){
var listItem = document.getElementById(item);
if(listItem.style.display == "none"){
listItem.style.display = "block";
} else {
listItem.style.display = "none";
}
},
render: function(){
return (
<ul className="list-group">
{this.props.recipes.map(
function(item,index){
return (
<li className="list-group-item" onClick={this.openRecipe(item)}>
<h4>{item.name}</h4>
<h5 className="text-center">Ingredients</h5>
<hr/>
<ul className="list-group" id={index} >
{item.ingredients.map(function(item){
return (
<li className="list-group-item">
<p>{item}</p>
</li>
)
})}
</ul>
</li>
)
}
)
}
</ul>
)
}
});
ReactDOM.render(<App />, document.getElementById('app'));
Also, I am trying to use a CSS method here, but maybe there is a better way to do it with React?
Can anyone help me? Thanks!
your issue is you are losing your this context in your map... you need to add .bind(this) to the end of your map function
{this.props.recipes.map(function(item,index){...}.bind(this))};
I answered another question very similar to this here. If you can use arrow functions it auto binds for you which is best. If you can't do that then either use a bind or make a shadow variable of your this context that you use inside the map function.
Now for the cleanup part. You need to clean up your code a bit.
var RecipeList = React.createClass({
getInitialState: function() {
return {display: []};
},
toggleRecipie: function(index){
var inArray = this.state.display.indexOf(index) !== -1;
var newState = [];
if (inArray) { // hiding an item
newState = this.state.display.filter(function(item){return item !== index});
} else { // displaying an item
newState = newState.concat(this.state.display, [index]);
}
this.setState({display: newState});
},
render: function(){
return (
<ul className="list-group">
{this.props.recipes.map(function(item,index){
var inArray = this.state.display.indexOf(index) !== -1;
return (
<li className="list-group-item" onClick={this.toggleRecipie.bind(this, index)}>
<h4>{item.name}</h4>
<h5 className="text-center">Ingredients</h5>
<hr/>
<ul className="list-group" id={index} style={{display: inArray ? 'block' : 'none'}} >
{item.ingredients.map(function(item){
return (
<li className="list-group-item">
<p>{item}</p>
</li>
)
}.bind(this))}
</ul>
</li>
)
}.bind(this))
}
</ul>
)
}
});
This may be a little complicated and you may not want to manage a list of indicies to toggle a view of ingredients. I'd recommend you make components for your code, this way its more react centric and it makes toggling a view much easier.
I'm going to write this in ES6 syntax also as you should be using ES6.
const RecipieList = (props) => {
return (
<ul className="list-group">
{props.recipes.map( (item,index) => <RecipieItem recipie={item} /> )
</ul>
);
};
class RecipieItem extends React.Component {
constructor(){
super();
this.state = {displayIngredients: false}
}
toggleRecipie = () => {
this.setState({displayIngredients: !this.state.displayIngredients});
}
render() {
return (
<li className="list-group-item" onClick={this.toggleRecipie}>
<h4>{item.name}</h4>
<h5 className="text-center">Ingredients</h5>
<hr/>
<ul className="list-group" style={{display: this.state.displayIngredients ? 'block' : 'none'}} >
{this.props.recipie.ingredients.map( (item) => <IngredientItem ingredient={item} /> )}
</ul>
</li>
);
}
}
const IngredientItem = (props) => {
return (
<li className="list-group-item">
<p>{props.ingredient}</p>
</li>
);
};
You also can use something like this:
render: function(){
var self = this;
return (
<ul className="list-group">
{this.props.recipes.map(
function(item,index){
return (
<li className="list-group-item" onClick={self.openRecipe(item)}>.....

React: Get target's DOM children

Let's say you have an HTML unordered list, and you'd like to create a React element from it:
<ul id="mylist">
<li>Something</li>
<li>Another thing</li>
<li>Third thing</li>
</ul>
then in JS:
ReactDOM.render(<MyNewList />, document.getElementById('mylist'));
I'd like to retrieve the original HTML LIs and use them in my MyNewList component. Something like:
class MyNewList extends React.Component {
componentWillMount() {
let listArray = this.props.whatever
}
...
}
Is that possible? How?
thanks.
Here is how you can achieve this: http://codepen.io/PiotrBerebecki/pen/BLbjEJ
It's a rough structure, so you would have to refactor it a bit so that it fits your desired use.
HTML:
<body>
<ul id="mylist">
<li>Something</li>
<li>Another thing</li>
<li>Third thing</li>
</ul>
</body>
JS:
class MyNewList extends React.Component {
constructor() {
super();
this.state = {
myList: null
};
}
componentWillMount() {
const myList = document.getElementById('mylist').children;
this.setState({
myList: myList
});
}
render() {
let renderList = 'Loading...'
if (this.state.myList) {
renderList = Array.prototype.map.call(this.state.myList, function(item) {
return (
<li>{item.textContent} found in HTML</li>
);
});
}
return (
<ul id="myNewlist">
{renderList}
</ul>
);
}
}
ReactDOM.render(
<MyNewList />,
document.getElementById('mylist')
);
Why not just have those Li's be a component themselves and use them where they are currently. That way you can reuse them anywhere else?
class MyNewList extends React.Component {
componentWillMount() {
let listArray = this.props.whatever
}
render() {
return (<ul id="mylist">
<li>Something</li>
<li>Another thing</li>
<li>Third thing</li>
</ul>)
}
}
then just pop this in wherever you want to use it.
This is my solution (though if someone else finds a better one please post!):
JS:
let target = document.getElementById('mylist');
let liArray = target.getElementsByTagName('li');
ReactDOM.render(<MyNewList list={liArray} />, target);
then in JSX
class MyNewList extends React.Component {
componentWillMount() {
let liArray = [...this.props.list], // converts nodelist into array
createMarkup = (el) => { return {__html: el}; }, // https://facebook.github.io/react/docs/dom-elements.html
convertedArray = liArray.map((slide) => {
return <div dangerouslySetInnerHTML={createMarkup(slide.outerHTML)} />;
});
this.setState({
list: convertedArray
});
}
...
}
There's a slightly annoying side effect of each item being wrapped in a <div>, but I'm tweaking the above so that the result is valid HTML5 syntax for my application.

Categories

Resources