I have the following:
import React from 'react';
import {render} from 'react-dom';
class TShirt extends React.Component {
render () {
return <div className="thsirt">{this.props.name}</div>;
}
}
class FirstName extends React.Component {
propTypes: {
name: React.PropTypes.string.isRequired
}
constructor(props) {
super(props);
this.state = {
submitted: false
};
}
getName () {
var name = this.refs.firstName.value;
this.setState(function() {
this.props.action(name);
});
}
handleSubmit (e) {
e.preventDefault();
this.setState({ submitted: true }, function() {
this.props.actionNav('color');
});
}
render () {
if(!this.state.submitted){
return (
<div>
<h2>tell us your first name</h2>
<form>
<input
type="text"
ref="firstName"
onChange={this.getName.bind(this)}
/>
<div className="buttons-wrapper">
back
<button onClick={this.handleSubmit.bind(this)}>continue</button>
</div>
</form>
</div>
);
}
else {
return <PickColor color={this.props.colorVal} />;
}
}
}
class Link extends React.Component {
setActiveClass () {
if(this.props.el == this.props.activeClass){
return 'active';
}
}
render () {
var active = this.setActiveClass();
return (
<li className={active}>{this.props.el}</li>
);
}
}
class Nav extends React.Component {
render () {
var links = ['name', 'color', 'design', 'share'],
newLinks = [],
that = this;
links.forEach(function(el){
newLinks.push(<Link activeClass={that.props.active} key={el} el={el} />);
});
return (
<ul>
{newLinks}
</ul>
);
}
}
class PickColor extends React.Component {
getColorValue(event) {
console.log(event.target.getAttribute("data-color"));
console.log(this);
//this.props.color(event.target.getAttribute("data-color"));
}
render () {
var colors = ['red', 'purple', 'yellow', 'green', 'blue'],
colorsLink = [],
that = this;
colors.forEach(function(el){
colorsLink.push(<li data-color={el} key={el} onClick={that.getColorValue} ref={el}>{el}</li>);
});
return (
<ul>
{colorsLink}
</ul>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
color: '',
active: ''
};
this.getName = this.getName.bind(this);
this.setActiveNav = this.setActiveNav.bind(this);
this.setColor = this.setColor.bind(this);
}
getName (tshirt) {
this.setState({ name:tshirt })
}
setActiveNav (active) {
this.setState({ active:active })
}
setColor (color) {
this.setState({ color:color })
}
render () {
return (
<section className={this.state.color}>
<Nav active={this.state.active} />
<TShirt name={this.state.name} />
<FirstName name={this.state.name} action={this.getName} actionNav={this.setActiveNav} colorVal={this.setColor} />
</section>
);
}
}
render(<App/>, document.getElementById('app'));
Inside the "PickColor" component I am trying to do this:
getColorValue(event) {
console.log(event.target.getAttribute("data-color"));
console.log(this);
//this.props.colorVal(event.target.getAttribute("data-color"));
}
however this is returning null on click so I can't go ahead ans use:
this.props.colorVal
The solution was here:
class PickColor extends React.Component {
getColorValue(event) {
console.log(event.target.getAttribute("data-color"));
this.props.color(event.target.getAttribute("data-color"));
}
render () {
var colors = ['red', 'purple', 'yellow', 'green', 'blue'],
colorsLink = [],
that = this;
colors.forEach(function(el){
colorsLink.push(<li data-color={el} key={el} onClick={that.getColorValue.bind(that)} ref={el}>{el}</li>);
});
return (
<ul>
{colorsLink}
</ul>
);
}
}
I had to bind "that" to the onClick inside the forEach loop
Issue is in this line:
onClick={that.getColorValue}
You forgot to bind the correct this (class context) with onClick event handler function because of that this.props is not accessible in getColorValue function.
Solutions:
Multiple Solutions are possible, use any one (all these changes are for PickColor component):
1- Inline binding of click handler:
onClick = { that.getColorValue.bind(this) }
2- Bind the method in the constructor:
constructor(props) {
super(props);
this.state = { };
this.getColorValue = this.getColorValue.bind(this);
}
3- Using arrow function:
onClick = {e => that.getColorValue(e) }
4- Using class property syntax:
onclick = {this.getColorValue}
getColorValue = (e) => {
console.log('e', this.props)
}
When you create a new function, like this:
function() {
this.props.action(name);
});
This is bind to the new function context. Every function has a different this in javascript. You can solve this in a few ways:
Use arrow functions if you have them (they won't rebind this)
() => {
this.props.action(name);
});
Rebind this with bind
function() {
this.props.action(name);
}.bind(this));
Save this in a variable
var that = this;
function() {
that.props.action(name);
});
Choose the first if you have a transpiler, like babel! Otherwise it's your call.
Related
I have the below where it should display images of beers retrieved from an API. Each image has a handleClick event which will direct them to a details page about this beer. My code below doesn't render the beers at all and goes straight to the details page of a random beer. Can anyone help me figure out why?
Thanks
export default class GetBeers extends React.Component {
constructor() {
super();
this.state = {
beers: [],
showMethod: false,
beerDetails: []
};
this.getBeerInfo = this.getBeerInfo.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleClick(details) {
this.setState({
showMethod: !this.state.showMethod,
beerDetails: details
});
}
render() {
if(this.state.showMethod) {
return (
<Beer details = {this.state.beerDetails}/>
);
}
else {
return (
<div>{this.state.beers.map(each=> {
return <img className = "img-beer" onClick = {this.handleClick(each)} src={each.image_url}/>
})}</div>
);
}
}
componentDidMount() {
this.getBeerInfo()
}
getBeerInfo() {
...gets info
}
}
When you use onClick like that you run the function at the render.
So you have to use arrow function:
Not Working:
<img className = "img-beer" onClick = {this.handleClick(each)} src={each.image_url}/>
Working:
<img className = "img-beer" onClick = {() => this.handleClick(each)} src={each.image_url}/>
The main issue is not calling the handle properly.
Also, I noticed that you are binding the functions in the constructor. It might be simpler to use ES6 function creation, so the scope of the class is bound to your handle method.
export default class GetBeers extends React.Component {
constructor() {
super();
this.state = {
beers: [],
showMethod: false,
beerDetails: []
};
}
handleClick = (details) => {
this.setState({
showMethod: !this.state.showMethod,
beerDetails: details
});
}
render() {
if(this.state.showMethod) {
return (
<Beer details = {this.state.beerDetails}/>
);
}
else {
return (
<div>{this.state.beers.map(each=> {
return <img className = "img-beer" onClick = {() => this.handleClick(each)} src={each.image_url}/>
})}</div>
);
}
}
componentDidMount() {
this.getBeerInfo()
}
getBeerInfo = () => {
...gets info
}
}
Let's say I've a parent component A and a child B:
A:
class A {
constructor() {
this.state = {data: []};
}
handleClick = () => {
// api call
// set data state to the returned value from api
// call B's createTable method
}
render() {
return(
<div>
<button onClick={()=> this.handleClick()}>Fetch data</button>
<B data={this.state.data} />
</div>
}
}
B:
class B {
constructor() {
this.state = {...};
}
createTable = () => {
const { data } = this.props;
// do smth
}
render() {
return(...);
}
}
I want to call createTable method from A without using Refs.
What I've done so far is using componentDidUpdate life cycle method in B to check if data prop has changed or not, If it changed call createTable method but I want to know is this right? or there's a better way of doing it because I feel it is kinda hacky or maybe bad design.
class B {
constructor() {
this.state = {...};
}
componentDidUpdate(prevProps) {
const { data } = this.props;
if (data !== prevProps.data) {
this.createTable();
}
}
createTable = () => {
const { data } = this.props;
// do smth
}
render() {
return(...);
}
}
NOTE I don't want to use hooks either just class based component.
The following example might be useful
class Parent extends Component {
render() {
return (
<div>
<Child setClick={click => this.clickChild = click}/>
<button onClick={() => this.clickChild()}>Click</button>
</div>
);
}
}
class Child extends Component {
constructor(props) {
super(props);
this.getAlert = this.getAlert.bind(this);
}
componentDidMount() {
this.props.setClick(this.getAlert);
}
getAlert() {
alert('clicked');
}
render() {
return (
<h1 ref="hello">Hello</h1>
);
}
}
I have a simple search bar which uses a react-autosuggest. When I create a suggestion, I want to attach an onClick handler. This onClick has been passed down from a parent class. When the suggestion is rendered however, this is undefined and therefore the click handler is not attached.
I have attached the component below, the logic which is not working is in the renderSuggestion method.
import Autosuggest from 'react-autosuggest'
import React from 'react'
export class SearchBar extends React.Component {
static getSuggestionValue(suggestion) {
return suggestion;
}
static escapeRegexCharacters(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
constructor(props) {
super(props);
this.state = {
value: '',
suggestions: [],
listOfValues: this.props.tickers
};
}
onChange = (event, { newValue, method }) => {
this.setState({
value: newValue
});
};
onSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: this.getSuggestions(value)
});
};
onSuggestionsClearRequested = () => {
this.setState({
suggestions: []
});
};
renderSuggestion(suggestion) {
return (
<span onClick={() => this.props.clickHandler(suggestion)}>{suggestion}</span>
);
}
getSuggestions(value) {
const escapedValue = SearchBar.escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return this.state.listOfValues.filter(ticker => regex.test(ticker));
}
render() {
const { value, suggestions } = this.state;
const inputProps = {
placeholder: "Search for stocks...",
value,
onChange: this.onChange
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={SearchBar.getSuggestionValue}
renderSuggestion={this.renderSuggestion}
inputProps={inputProps} />
);
}
}
This is becuase you need to bind "this" to your function.
If you add this code to your constructor
constructor(props) {
super(props);
this.state = {
value: '',
suggestions: [],
listOfValues: this.props.tickers
};
//this line of code binds this to your function so you can use it
this.renderSuggestion = this.renderSuggestion.bind(this);
}
It should work. More info can be found at https://reactjs.org/docs/handling-events.html
In the scope of renderSuggestion, this isn't referring to the instance of the class.
Turning renderSuggestion into an arrow function like you've done elsewhere will ensure that this refers to the instance of the class.
renderSuggestion = (suggestion) => {
return (
<span onClick={() => this.props.clickHandler(suggestion)}>{suggestion}</span>
);
}
I'm beginner on react and i've written the code below:
class Note extends React.Component {
constructor(props) {
super(props);
this.state = {editing: false};
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
edit() {
// alert('edit');
this.setState({editing: !this.state.editing});
}
save() {
this.props.onChange(this.refs.newVal.value, this.props.id);
this.setState({editing: !this.state.editing});
// console.log('save is over');
}
renderForm() {
return (
<div className="note">
<textarea ref="newVal"></textarea>
<button onClick={this.save}>SAVE</button>
</div>
);
}
renderDisplay() {
return (
<div className="note">
<p>{this.props.children}</p>
<span>
<button onClick={this.edit}>EDIT</button>
<button onClick={this.remove}>X</button>
</span>
</div>
);
}
render() {
console.log(this.state.editing);
return (this.state.editing) ? this.renderForm()
: this.renderDisplay()
}
}
class Board extends React.Component {
constructor(props){
super(props);
this.state = {
notes: []
};
this.update = this.update.bind(this);
this.eachNote = this.eachNote.bind(this);
this.add = this.add.bind(this);
}
nextId() {
this.uniqeId = this.uniqeId || 0;
return this.uniqeId++;
}
add(text) {
let notes = [
...this.state.notes,
{
id: this.nextId(),
note: text
}
];
this.setState({notes});
}
update(newText, id) {
let notes = this.state.notes.map(
note => (note.id !== id) ?
note :
{
id: id,
note: newText
}
);
this.setState({notes})
}
eachNote(note) {
return (<Note key={note.id}
id={note.id}
onChange={this.update}>
{note.note}
</Note>)
}
render() {
return (<div className='board'>
{this.state.notes.map(this.eachNote)}
<button onClick={() => this.add()}>+</button>
</div>)
}
}
ReactDOM.render(<Board />,
document.getElementById('root'));
In render(), onClick event has a function, that is, if used in this way: {this.add} the following error is created:
Uncaught Error: Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, nativeEvent, type, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, ...})
Why? while in the eachNote() method this command is used:
onChange={this.update}
And there was no error.
Someone can tell me the reason? thanks.
The problem is that in the add function you are taking an argument text and setting it in the state so when you call onClick={() => this.add()}, you are not passing any argument to add function and hence in its definition text is undefned and hence state note is set as undefined.
However if you directly call it like onClick={this.add} , the add function receives the event object as a parameter and hence it sets state note to be an event object which you are using to render
onClick={this.add} will pass the click event to this.add.
So what you need to do is either:
onClick={e => this.add('some text')} or similar.
If you want to onClick={this.add} you have to ensure that your add method is: add(event) { ... } instead.
The <Note /> component does not contain a render() method to return anything. Add a render() method and return something.
class Note extends React.Component {
constructor(props) {
super(props);
this.state = {editing: false};
this.edit = this.edit.bind(this);
}
edit() {
// alert('edit');
this.setState({editing: !this.state.editing});
}
render() {
return (
<div>Render something</div>
)
}
}
class Board extends React.Component {
constructor(props){
super(props);
this.state = {
notes: []
};
this.update = this.update.bind(this);
this.eachNote = this.eachNote.bind(this);
this.add = this.add.bind(this);
}
nextId() {
this.uniqeId = this.uniqeId || 0;
return this.uniqeId++;
}
add(text) {
let notes = [
...this.state.notes,
{
id: this.nextId(),
note: text
}
];
this.setState({notes});
}
update(newText, id) {
let notes = this.state.notes.map(
note => (note.id !== id) ?
note :
{
id: id,
note: newText
}
);
this.setState({notes})
}
eachNote(note) {
return (<Note key={note.id}
id={note.id}
onChange={this.update}>
{note.note}
</Note>)
}
render() {
return (<div className='board'>
{this.state.notes.map(this.eachNote)}
<button onClick={() => this.add()}>+</button>
</div>)
}
}
ReactDOM.render(<Board />,
document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="root"></div>
I study FLUX and try to write simple example on it. It is about a menu where I can select every single item (it is marked by (*)). So, here is main excerpts of the code:
AppContainer.js:
class AppContainer extends React.Component
{
static getStores() {
return [MenuStore];
}
static calculateState(prevState) {
return {
menu: MenuStore.getState(),
onclick: Actions.onclick
};
}
render() {
return <MenuView onclick={this.state.onclick} menu={this.state.menu.get('list')} cur={this.state.menu.get('cur')} />;
}
}
MenuStore.js
class MenuStore extends ReduceStore{
constructor() {
super(MenuDispatcher);
}
getInitialState() {
// return {list: ["About", "Contacts", "Price", "Home"], cur: 0};
return Immutable.Map({list: ["About", "Contacts", "Price", "Home"], cur: 2});
}
reduce(state, action) {
switch (action.type) {
case ActionTypes.ON_CLICK:
console.log('MenuStone ON_CLICK');
state.cur = action.index;
return state;
default:
return state;
}
}
}
MenuView.js:
class MenuView extends React.Component{
constructor(props){
super(props);
}
render(){
return <ui>{this.props.menu.map((menu, index) => {
var active = (this.props.cur === index) ? true : false;
return <MenuItem onclick={this.props.onclick} key={index} index={index} active={active} label={menu} />;
})}</ui>;
}
}
class MenuItem extends React.Component {
constructor(props) {
super(props);
this.state = {label: props.label};
this.click = this.click.bind(this);
}
click(index) {
console.log('MenuItem click');
this.props.onclick(this.props.index);
}
render() {
var mark = '';
if (this.props.active)
mark = '(*) ';
return <li onClick={this.click}>{mark}{this.state.label}</li>;
}
}
Actions.js:
const Actions = {
onclick(index) {
console.log('Actions.onclick');
MenuDispatcher.dispatch({
type: ActionTypes.ON_CLICK,
index,
});
}
};
When I run the code, it is work fine until I click a menu item. The code
state.cur = action.index;
executes, but nothing changes on the page.
What should I do to update the views?