React Rerender dynamic Components (Solr) - javascript

I am somewhat new to ReactJS
I have a react class that is rendering a number of items: (Sample)
var app = app || {};
app.Results = React.createClass({
componentDidMount: function () {
},
handleUpdateEvent: function(id){
var _self = this;
var handler = function()
{
var query = _self.props.results.query;
_self.props.onSearch(query); // re-does the search to re-render items ...
// obviously this is wrong since I have to click the button twice to see the results
//
}
var optionsURL = {dataType: 'json'};
optionsURL.type= 'POST';
optionsURL.url = 'http://localhost:8983/solr/jcg/dataimport?command=delta-import&clean=false&commit=true&json.nl=map&wt=json&json.wrf=?&id='+id;
// updates index for specific item.
jQuery.ajax(optionsURL).done(handler);
},
render: function () {
var tdLabelStyle = {
width: '150px'
}
return (
<div id="results-list">
{this.props.results.documents.map(function (item) {
return (
<div id={item.id} key={item.id} className="container-fluid result-item">
<div className="row">
<div className="col-md-6">
<table>
<tr><td colspan="2">{item.name}</td></tr>
<tr style={{marginTop:'5px'}}><td style={tdLabelStyle}><b>Amount:</b></td><td>{item.amount}
<button type="Submit" onClick={() => {this.handleUpdateEvent(item.id)}} title="Refresh Amount" >Refresh</button>
</td></tr>
</table>
</div>
</div>
</div>
)
},this)}
</div>
);
}
});
I have a button within the table that makes a call out to SOLR to perform a delta import, then re-calls the select function in order to grab the new data.
I'm obviously doing the handleUpdateEvent function incorrectly, however, I'm not 100% sure how to go about getting either the entire thing to re-render, or just the individual item to re-render.
(Hopefully I've made sense...)
Any help is appreciated.
(onSearch Function)
handleSearchEvent: function (query) {
if (this.state.query != null)
{
if (this.state.query.filters != null)
{
query.filters = this.state.query.filters;
}
}
$("#load-spinner-page").show();
if (app.cache.firstLoad) {
$("body").css("background","#F8F8F8");
app.cache.firstLoad = false;
}
var _self = this;
app.cache.query = query;
docSolrSvc.querySolr(query, function(solrResults) {
_self.setState({query: query, results: solrResults});
$("#load-spinner-page").hide();
});
},

The first thing to change is the use of React.createClass. This has been depracated in favour ES6 syntax. Also, I dont't suggest using jQuery along side React. It's not impossible to do, but there are other things to consider. Read this for more. I'll use it here, but consider something like fetch or axios (or one of the many other libraries) for fetching the data.
I think you're on the right track, but a few things to update. Because the available options are changing, I would put them into the components state, then having the handleUpdateEvent function update the state, which will trigger a re-render.
Your class would look something like this:
class Results extends React.Component {
constructor(props) {
super(props);
// this sets the initial state to the passed in results
this.state = {
results: props.results
}
}
handleUpdateEvent(id) {
const optionsURL = {
dataType: 'json',
type: 'POST',
url: `http://localhost:8983/solr/jcg/dataimport?command=delta-import&clean=false&commit=true&json.nl=map&wt=json&json.wrf=?&id=${ id }`
};
// Instead of calling another function, we can do this right here.
// This assumes the `results` from the ajax call are the same format as what was initially passed in
jQuery.ajax(optionsURL).done((results) => {
// Set the component state to the new results, call `this.props.onSearch` in the callback of `setState`
// I don't know what `docSolrSvc` is, so I'm not getting into the `onSearch` function
this.setState({ results }, () => {
this.props.onSearch(results.query);
});
});
}
render() {
const tdLabelStyle = {
width: '150px'
};
// use this.state.results, not this.props.results
return (
<div id="results-list">
{
this.state.results.documents.map((item) => (
<div>
<div id={ item.id } key={ item.id } className="container-fluid result-item">
<div className="row">
<div className="col-md-6">
<table>
<tr><td colspan="2">{item.name}</td></tr>
<tr style={{marginTop:'5px'}}>
<td style={ tdLabelStyle }><b>Amount:</b></td>
<td>{item.amount}
<button type="button" onClick={ () => { this.handleUpdateEvent(item.id) } } title="Refresh Amount" >Refresh</button>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
))
}
</div>
);
}
}

Related

React DOM not re-rendering/updating after state change

The current state object is this:
this.state = {
loadedPostList: [],
top: 0,
end: 0,
thresh: 20,
page: 0,
loadingPostList: false,
filter: [],
lazying: false
};
I'm utilising some react lifecycle methods to control my redux store updates, and dataflow:
shouldComponentUpdate(nextProps, nextState) {
return this.props.posts.loadedPosts !== nextProps.posts.loadedPosts || this.state.loadedPostList !== nextState.loadedPostList;
}
componentDidUpdate(prevProps) {
let { loadedPosts, changeEvent, updatedId, deleteId } = this.props.posts;
if(prevProps.posts.loadedPosts !== loadedPosts) {
switch(changeEvent) {
case 'insert':
if(this.state.top === 0) {
this.refreshList();
}
console.log('new post in thread...');
break;
case 'update':
this.refreshList();
console.log('post updated in thread...');
break;
case 'delete':
this.refreshList();
console.log('post deleted in thread...');
break;
default:
break;
}
}
}
refreshList = () => {
let newList = this.props.posts.loadedPosts.slice(this.state.top, this.state.end);
this.setState({
loadedPostList: [...newList]
}, () => {
console.log('refreshed post list')
})
}
And in the render function, I'm mapping the elements of this.state.loadedPostList to PostList components. The problem is that when my redux store updates, and subsequently my this.state.loadedPostList, the mapping in re-render doesn't update to show the updated array. Logging to the console and observing the redux actions and store via redux dev tools show that the array is indeed updating correctly, and the functions such us refreshList() are working as they should. However, the problem remains with the DOM not re-rendering/updating according to the state changes. The render function:
render() {
return (
<div id="question-list-wrapper">
{
this.state.loadingPostList || this.state.lazying ?
<MiniViewLoader textToRender="Loading questions..."/>
:
<div id="question-list-inner-wrapper">
<div id="question-list-inner-wrapper-nav">
<h1 className="text" id='inner-wrapper-nav-header'> Recent Questions </h1>
</div>
{
this.state.loadedPostList.length < 1 ? <h1 className="no-questions-text">No questions availabe</h1> : ""
}
{
this.state.loadedPostList.map((post, index) => {
return (
<PostSlot idx={index} key={index+""} postData={post}/>
)
})
}
<div id="question-list-write-btn" alt="Ask Question">
<span>Ask Question</span>
<WritePostButton />
</div>
</div>
}
</div>
)
}
(EDIT) Further information if it helps. The component with the issue is being rendered by a react router Switch wrapper inside the render() function of another component.
The Other Component:
render() {
return(
<div className="page-wrapper">
{
this.state.settingUp ?
<FullPageLoaderWithText textToRender="Setting things up for you..."/>
:
<div id="main-hoc-wrapper-inner-wrapper">
<div id="main-hoc-nav-bar" className="item-a">
<span id="main-hoc-nav-logo" className="main-hoc-nav-elem">
PA
</span>
<span id="main-hoc-nav-search" className="main-hoc-nav-elem">
<input type="text" placeholder="Search..." className="placeholderEdit"/>
</span>
</div>
<div id="main-hoc-sidebar" className="item-c">
<span className="main-hoc-sidebar-tabs">{this.props.user.data}</span>
<span className="main-hoc-sidebar-tabs">tags</span>
<span className="main-hoc-sidebar-tabs">community</span>
<span className="main-hoc-sidebar-tabs">opportunities</span>
</div>
<div id="main-hoc-main-view" className="item-b">
<Switch>
{/* <Route path="/:param1/:param2/path" component={QuestionList} /> */}
<Route path="/:param1/:param2/path" render={() => <QuestionList connect={socket}/>} />
</Switch>
</div>
<div id="main-hoc-right-bar" className="item-d">
Blog posts & ads
</div>
</div>
}
</div>
)
}
I think the problem is your if condition, you cannot compare two array with !==.
Example:
var t = [1,2,3];
var f = [1,2,3];
if (t !== f) {
console.log("different");
} else {
console.log("same");
}
// by your logic the output should be "same"
// but it will not be
// because internally they both are object and we cannot compare
// two objects using `===` operator.
// you will have to loop through and check for difference
// or better let REACT HANDLE SUCH THINGS
the problem is in this line
let newList = this.props.posts.loadedPosts.slice(this.state.top, this.state.end);,
this.state.top and this.state.end is both 0, so it will always return an empty array, make sure you are updating the top and end after each refresh.

Unable to render html divs with React?

I'm trying to generate several divs based off an array - but I'm unable to. I click a button, which is supposed to return the divs via mapping but it's returning anything.
class History extends Component {
constructor(props) {
super(props);
this.state = {
info: ""
};
this.generateDivs = this.generateDivs.bind(this);
}
async getCurrentHistory(address) {
const info = await axios.get(`https://api3.tzscan.io/v2/bakings_history/${address}?number=10000`);
return info.data[2];
}
async getHistory() {
const info = await getCurrentHistory(
"tz1hAYfexyzPGG6RhZZMpDvAHifubsbb6kgn"
);
this.setState({ info });
}
generateDivs() {
const arr = this.state.info;
const listItems = arr.map((cycles) =>
<div class="box-1">
Cycle: {cycles.cycle}
Count: {cycles.count.count_all}
Rewards: {cycles.reward}
</div>
);
return (
<div class="flex-container">
{ listItems }
</div>
)
}
componentWillMount() {
this.getHistory();
}
render() {
return (
<div>
<button onClick={this.generateDivs}>make divs</button>
</div>
);
}
You are not actually rendering the the divs just by invoking the generateDivs function, the JSX it is returning is not being used anywhere.
To get it to work you could do something like -
render() {
return (
<div>
<button onClick={this.showDivs}>make divs</button>
{this.state.isDisplayed && this.generateDivs()}
</div>
);
}
where showDivs would be a function to toggle the state property isDisplayed to true
The main point is that the JSX being returned in the generateDivs function will now be rendered out in the render function. There is many ways to toggle the display, that is just one straight forward way

Updating a React list without re-rendering said list

I'm trying to figure out how to render out a set of divs, without re-rendering the entire list as a new set is added.
So I've got a stateful component. Inside said stateful component, I've got a function that A, gets a list of post id's, and B, makes a request to each of those post id's and pushes the results to an array. Like so:
getArticles = () => {
axios.get(`${api}/topstories.json`)
.then(items => {
let articles = items.data;
let init = articles.slice(0,50);
init.forEach(item => {
axios.get(`${post}/${item}.json`)
.then(article => {
this.setState({ articles: [...this.state.articles, article.data]});
});
})
});
}
Then, I've got a second function that takes this information and outputs it to a list of posts. Like so:
mapArticles = () => {
let articles = this.state.articles.map((item, i) => {
let time = moment.unix(item.time).fromNow();
return(
<section className="article" key={i}>
<Link className="article--link" to={`/posts/${item.id}`}/>
<div className="article--score">
<FontAwesomeIcon icon="angle-up"/>
<p>{item.score}</p>
<FontAwesomeIcon icon="angle-down"/>
</div>
<div className="article--content">
<div className="article--title">
<h1>{item.title}</h1>
</div>
<div className="article--meta">
{item.by} posted {time}. {item.descendants ? `${item.descendants} comments.` : null}
</div>
</div>
<div className="article--external">
<a href={item.link} target="_blank">
<FontAwesomeIcon icon="external-link-alt"/>
</a>
</div>
</section>
)
});
return articles;
}
I then use {this.mapArticles()} inside the render function to return the appropriate information.
However, whenever the app loads in a new piece of data, it re-renders the entire list, causing a ton of jank. I.e., when the first request finishes, it renders the first div. When the second request finishes, it re-renders the first div and renders the second. When the third request finishes, it re-renders the first and second, and renders the third.
Is there a way to have React recognize that the div with that key already exists, and should be ignored when the state changes and the function runs again?
A technique that I use to only render the part that are new is to keep a cache map of already drawn obj, so in the render method I only render the new incoming elements.
Here is an example:
Take a look at https://codesandbox.io/s/wq2vq09pr7
In this code you can see that the List has an cache array and the render method
only draw new arrays
class RealTimeList extends React.Component {
constructor(props) {
super(props);
this.cache = [];
}
renderRow(message, key) {
return <div key={key}>Mesage:{key}</div>;
}
renderMessages = () => {
//let newMessages=this,props.newMessage
let newElement = this.renderRow(this.props.message, this.cache.length);
this.cache.push(newElement);
return [...this.cache];
};
render() {
return (
<div>
<div> Smart List</div>
<div className="listcontainer">{this.renderMessages()}</div>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { message: "hi" };
}
start = () => {
if (this.interval) return;
this.interval = setInterval(this.generateMessage, 200);
};
stop = () => {
clearTimeout(this.interval);
this.interval = null;
};
generateMessage = () => {
var d = new Date();
var n = d.getMilliseconds();
this.setState({ title: n });
};
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={this.start}> Start</button>
<button onClick={this.stop}> Stop</button>
<RealTimeList message={this.state.message} />
</div>
);
}
}
If items arrive at the same time, wait till all items are fetched, then render:
getArticles = () => {
axios.get(`${api}/topstories.json`)
.then(items => {
let articles = items.data;
let init = articles.slice(0, 50);
Promise.all(init.map(item => axios.get(`${post}/${item}.json`)).then(articles => {
this.setState({
articles
});
})
});
}
If you really want to render immediately after an item is fetched, you can introduce a utility component that renders when promise resolves.
class RenderOnResolve extends React.Component {
state = null
componentDidMount() {
this.props.promise.then(data => this.setState(data))
}
render() {
return this.state && this.props.render(this.state);
}
}
// usage:
<RenderOnResolve promise={promise} render={this.articleRenderer}/>

Fuzzy search with Fuzzy.js and Tables? ReactJS

So I'm trying to use Fuzzy for my fuzzy search thing I have going on but it is very slow and doesn't seem like my states are updating on time. Here is a CodeSandbox with everything, and here is a snippet of my App.js:
const uuidv4 = require('uuid/v4');
var fuzzy = require('fuzzy');
console.log(fuzzy)
var searching = false;
class App extends Component {
constructor(props){
super(props);
this.state = {
searchWord: "",
searchMatches: []
}
this.fuzzySearch = this.fuzzySearch.bind(this);
this.handleChange = this.handleChange.bind(this);
}
//fuzzy search
fuzzySearch () {
var list = keywords.keywords;
var options = {
pre: '<b>'
, post: '</b>'
, extract: function(el) { return el.action; }
};
var results = fuzzy.filter(this.state.searchWord, list, options);
var matches = results.map(function(el) { return el.string; });
this.setState({searchMatches: matches});
console.log(this.state.searchMatches);
// [ '<b>a<c>o<n>ing', 'a mighty <b>ear <c>a<n>oe' ]
}
handleChange(event) {
this.setState({searchWord: event.target.value});
this.fuzzySearch()
}
render() {
const labelId = uuidv4();
return (
<div>
<div className="App">
<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="form">
<Search handleChange={this.handleChange} searchWord={this.state.searchWord}/>
<WordTable searchMatches={this.state.searchMatches}/>
</div>
</div>
);
}
}
class Search extends Component {
constructor(props){
super(props);
this.state = {
}
}
render () {
return (
<div id="searchDiv">
<input id="searchBar" type="text" placeholder="Search Keyword and/or Action..." value={this.props.searchWord} name="searchWord" onChange={this.props.handleChange}/>
</div>
);
}
}
class WordTable extends Component {
constructor(props) {
super(props);
this.results = this.results.bind(this);
}
results() {
console.log("result");
console.log(this.props.searchMatches.length)
if(this.props.searchMatches.length > 0){
var matches = this.props.searchMatches;
return (
matches.map(p =>
<Row key={uuidv4()} action={p.action} keyword={p.keyword}/>
)
)
} else {
return(
keywords.keywords.map(p =>
<Row key={uuidv4()} action={p.action} keyword={p.keyword}/>
)
)
}
}
render () {
return (
<div id="table">
<table>
<thead>
<tr>
<th>Action</th>
<th>Keyword(s)</th>
</tr>
</thead>
<tbody>
{/*console.log(keywords.keywords[0])}
{keywords.keywords.map((keyword, action) =>
<Row keyword={keywords.keywords.keyword} action={keywords.keywords.action}/>
)*/
this.results()
}
</tbody>
</table>
{JSON.stringify(this.props.actions, null, " ")}
</div>
);
}
}
class Row extends Component {
render () {
return (
<tr>
<td key={uuidv4()} value={this.props.action}>{this.props.action}</td>
<td key={uuidv4()} value={this.props.keyword}>{this.props.keyword}</td>
</tr>
)
}
}
export default App;
I am not sure why my search is making my React app slow, it also doesn't seem like the matches or searchMathes variable/state are updating on time, but could it be just that console.log is doing something funky? I am new to React and JS so any explanation of what's going on or what you think might be going on would help a lot.
And on top of the search being very slow, my results don't show up in my WordTable table. Any ideas as to why?
And an explanation of my JSON, the actual file I am using has 6000+ objects in it that look like
{ "action": "this-is-the-action", "keyword": "this is the keyword"}
I just put some random ones in the CodeSandbox I made there, But the idea is that there are duplicate actions to different keywords. I hope that explains that a little better. Thanks!
There were a number of things wrong with your initial solution.
as I said in my comment, this.setState is asynchronous/batched
following,
this.setState({ searchWord: event.target.value })
this.fuzzySearch()
might not (aka probably wont) work. Why? Because the time between this.setState(...) and accessing this.state.searchWord in fuzzySearch is small enough that React probably hasn't reconciled the new state yet.
your WordTable component was super wonky. You were passing a string[], but it expected the original objects (with a shape like { action: string, keyword: string }). You were also re-rendering all options if there were no matches... not sure if that was intended behaviour but it made it seem like everything matched when, in fact, nothing did.
not really a problem so much as an optimisation but there's really no point in computing and storing the filtered list - just compute it and pass it down as a prop after searchWord has changed. This also takes away the race condition in #1.
Here's a working example with all of the above implemented (a cleaned up a little).

React js onClick can't pass value to method

I want to read the onClick event value properties. But when I click on it, I see something like this on the console:
SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: ".1.1.0.2.0.0:1", nativeEvent: MouseEvent, type: "click", target
My code is working correctly. When I run I can see {column} but can't get it in the onClick event.
My Code:
var HeaderRows = React.createClass({
handleSort: function(value) {
console.log(value);
},
render: function () {
var that = this;
return(
<tr>
{this.props.defaultColumns.map(function (column) {
return (
<th value={column} onClick={that.handleSort} >{column}</th>
);
})}
{this.props.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column[0];
return ( <th>{externalColumnName}</th>);
})}
</tr>
);
}
});
How can I pass a value to the onClick event in React js?
Easy Way
Use an arrow function:
return (
<th value={column} onClick={() => this.handleSort(column)}>{column}</th>
);
This will create a new function that calls handleSort with the right params.
Better Way
Extract it into a sub-component.
The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.
If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):
Sub-component
class TableHeader extends Component {
handleClick = () => {
this.props.onHeaderClick(this.props.value);
}
render() {
return (
<th onClick={this.handleClick}>
{this.props.column}
</th>
);
}
}
Main component
{this.props.defaultColumns.map((column) => (
<TableHeader
value={column}
onHeaderClick={this.handleSort}
/>
))}
Old Easy Way (ES5)
Use .bind to pass the parameter you want, this way you are binding the function with the Component context :
return (
<th value={column} onClick={this.handleSort.bind(this, column)}>{column}</th>
);
There are nice answers here, and i agree with #Austin Greco (the second option with separate components)
There is another way i like, currying.
What you can do is create a function that accept a parameter (your parameter) and returns another function that accepts another parameter (the click event in this case). then you are free to do with it what ever you want.
ES5:
handleChange(param) { // param is the argument you passed to the function
return function (e) { // e is the event object that returned
};
}
ES6:
handleChange = param => e => {
// param is the argument you passed to the function
// e is the event object that returned
};
And you will use it this way:
<input
type="text"
onChange={this.handleChange(someParam)}
/>
Here is a full example of such usage:
const someArr = ["A", "B", "C", "D"];
class App extends React.Component {
state = {
valueA: "",
valueB: "some initial value",
valueC: "",
valueD: "blah blah"
};
handleChange = param => e => {
const nextValue = e.target.value;
this.setState({ ["value" + param]: nextValue });
};
render() {
return (
<div>
{someArr.map(obj => {
return (
<div>
<label>
{`input ${obj} `}
</label>
<input
type="text"
value={this.state["value" + obj]}
onChange={this.handleChange(obj)}
/>
<br />
<br />
</div>
);
})}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<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>
<div id="root"></div>
Note that this approach doesn't solve the creation of a new instance on each render.
I like this approach over the other inline handlers as this one is more concise and readable in my opinion.
Edit:
As suggested in the comments below, you can cache / memoize the result of the function.
Here is a naive implementation:
let memo = {};
const someArr = ["A", "B", "C", "D"];
class App extends React.Component {
state = {
valueA: "",
valueB: "some initial value",
valueC: "",
valueD: "blah blah"
};
handleChange = param => {
const handler = e => {
const nextValue = e.target.value;
this.setState({ ["value" + param]: nextValue });
}
if (!memo[param]) {
memo[param] = e => handler(e)
}
return memo[param]
};
render() {
return (
<div>
{someArr.map(obj => {
return (
<div key={obj}>
<label>
{`input ${obj} `}
</label>
<input
type="text"
value={this.state["value" + obj]}
onChange={this.handleChange(obj)}
/>
<br />
<br />
</div>
);
})}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<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>
<div id="root" />
Nowadays, with ES6, I feel we could use an updated answer.
return (
<th value={column} onClick={()=>this.handleSort(column)} >{column}</th>
);
Basically, (for any that don't know) since onClick is expecting a function passed to it, bind works because it creates a copy of a function. Instead we can pass an arrow function expression that simply invokes the function we want, and preserves this. You should never need to bind the render method in React, but if for some reason you're losing this in one of your component methods:
constructor(props) {
super(props);
this.myMethod = this.myMethod.bind(this);
}
[[h/t to #E.Sundin for linking this in a comment]
The top answer (anonymous functions or binding) will work, but it's not the most performant, as it creates a copy of the event handler for every instance generated by the map() function.
This is an explanation of the optimal way to do it from the ESLint-plugin-react:
Lists of Items
A common use case of bind in render is when rendering a list, to have
a separate callback per list item:
const List = props => (
<ul>
{props.items.map(item =>
<li key={item.id} onClick={() => console.log(item.id)}>
...
</li>
)}
</ul>
);
Rather than doing it this way, pull the repeated section into its own
component:
const List = props => (
<ul>
{props.items.map(item =>
<ListItem
key={item.id}
item={item}
onItemClick={props.onItemClick} // assume this is passed down to List
/>
)}
</ul>
);
const ListItem = props => {
const _onClick = () => {
console.log(props.item.id);
}
return (
<li onClick={_onClick}>
...
</li>
);
});
This will speed up rendering, as it avoids the need to create new
functions (through bind calls) on every render.
This is my approach, not sure how bad it is, please comment
In the clickable element
return (
<th value={column} onClick={that.handleSort} data-column={column}> {column}</th>
);
and then
handleSort(e){
this.sortOn(e.currentTarget.getAttribute('data-column'));
}
React Hooks Solution 2022
const arr = [
{ id: 1, txt: 'One' },
{ id: 2, txt: 'Two' },
{ id: 3, txt: 'Three' },
]
const App = () => {
const handleClick = useCallback(
(id) => () => {
console.log("ID: ", id)
},
[],
)
return (
<div>
{arr.map((item) => (
<button onClick={handleClick(item.id)}>{item.txt}</button>
))}
</div>
)
}
You can pass a function to useCallback's return, you can then call your function normally in the render by passing params to it. Works like a charm! Just make sure you set your useCallback's dependency array appropriately.
Best Solution with React >= 16
The cleanest way I've found to call functions with multiple parameters in onClick, onChange etc. without using inline functions is to use the custom data attribute available in React 16 and above versions.
const App = () => {
const onClick = (e) => {
const value1 = e.currentTarget.getAttribute("data-value1")
const value2 = e.currentTarget.getAttribute("data-value2")
const value2 = e.currentTarget.getAttribute("data-value2")
console.log("Values1", value1)
console.log("Values2", value2)
console.log("Values3", value3)
}
return (
<button onClick={onClick} data-value1="a" data-value2="b" data-value3="c" />
)
}
Above example is for a functional component but the implementation is pretty similar even in class components.
This approach doesn't yield unnecessary re-renders because you aren't using inline functions, and you avoid the hassle of binding with this.
It allows you to pass as many values as you would like to use in your function.
If you are passing values as props to your children to be used in the Child Component's onClick, you can use this approach there as well, without creating a wrapper function.
Works with array of objects as well, in cases where you want to pass the id from the object to the onClick, as shown below.
const App = () => {
const [arrState, setArrState] = useState(arr)
const deleteContent = (e) => {
const id = e.currentTarget.getAttribute("data-id")
const tempArr = [...arrState]
const filteredArr = tempArr.filter((item) => item.id !== id)
setArrState(filteredArr)
}
return (
<div>
{arrState.map((item) => (
<React.Fragment key={item.id}>
<p>{item.content}</p>
<button onClick={deleteContent} data-id={item.id}>
Delete
</button>
</React.Fragment>
))}
</div>
)
}
this example might be little different from yours. but i can assure you that this is the best solution you can have for this problem.
i have searched for days for a solution which has no performance issue. and finally came up with this one.
class HtmlComponent extends React.Component {
constructor() {
super();
this.state={
name:'MrRehman',
};
this.handleClick= this.handleClick.bind(this);
}
handleClick(event) {
const { param } = e.target.dataset;
console.log(param);
//do what you want to do with the parameter
}
render() {
return (
<div>
<h3 data-param="value what you wanted to pass" onClick={this.handleClick}>
{this.state.name}
</h3>
</div>
);
}
}
UPDATE
incase you want to deal with objects that are supposed to be the parameters. you can use JSON.stringify(object) to convert to it to string and add to the data set.
return (
<div>
<h3 data-param={JSON.stringify({name:'me'})} onClick={this.handleClick}>
{this.state.name}
</h3>
</div>
);
Simply create a function like this
function methodName(params) {
//the thing you wanna do
}
and call it in the place you need
<Icon onClick = {() => { methodName(theParamsYouwantToPass);} }/>
class extends React.Component {
onClickDiv = (column) => {
// do stuff
}
render() {
return <div onClick={() => this.onClickDiv('123')} />
}
}
I realize this is pretty late to the party, but I think a much simpler solution could satisfy many use cases:
handleEdit(event) {
let value = event.target.value;
}
...
<button
value={post.id}
onClick={this.handleEdit} >Edit</button>
I presume you could also use a data- attribute.
Simple, semantic.
Making alternate attempt to answer OP's question including e.preventDefault() calls:
Rendered link (ES6)
<a href="#link" onClick={(e) => this.handleSort(e, 'myParam')}>
Component Function
handleSort = (e, param) => {
e.preventDefault();
console.log('Sorting by: ' + param)
}
One more option not involving .bind or ES6 is to use a child component with a handler to call the parent handler with the necessary props. Here's an example (and a link to working example is below):
var HeaderRows = React.createClass({
handleSort: function(value) {
console.log(value);
},
render: function () {
var that = this;
return(
<tr>
{this.props.defaultColumns.map(function (column) {
return (
<TableHeader value={column} onClick={that.handleSort} >
{column}
</TableHeader>
);
})}
{this.props.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column[0];
return ( <th>{externalColumnName}</th>
);
})}
</tr>);
)
}
});
// A child component to pass the props back to the parent handler
var TableHeader = React.createClass({
propTypes: {
value: React.PropTypes.string,
onClick: React.PropTypes.func
},
render: function () {
return (
<th value={this.props.value} onClick={this._handleClick}
{this.props.children}
</th>
)
},
_handleClick: function () {
if (this.props.onClick) {
this.props.onClick(this.props.value);
}
}
});
The basic idea is for the parent component to pass the onClick function to a child component. The child component calls the onClick function and can access any props passed to it (and the event), allowing you to use any event value or other props within the parent's onClick function.
Here's a CodePen demo showing this method in action.
You can simply do it if you are using ES6.
export default class Container extends Component {
state = {
data: [
// ...
]
}
handleItemChange = (e, data) => {
// here the data is available
// ....
}
render () {
return (
<div>
{
this.state.data.map((item, index) => (
<div key={index}>
<Input onChange={(event) => this.handItemChange(event,
item)} value={item.value}/>
</div>
))
}
</div>
);
}
}
There are couple of ways to pass parameter in event handlers, some are following.
You can use an arrow function to wrap around an event handler and pass parameters:
<button onClick={() => this.handleClick(id)} />
above example is equivalent to calling .bind or you can explicitly call bind.
<button onClick={this.handleClick.bind(this, id)} />
Apart from these two approaches, you can also pass arguments to a function that is defined as a curry function.
handleClick = (id) => () => {
console.log("Hello, your ticket number is", id)
};
<button onClick={this.handleClick(id)} />
Implementing show total count from an object by passing count as a parameter from main to sub components as described below.
Here is MainComponent.js
import React, { Component } from "react";
import SubComp from "./subcomponent";
class App extends Component {
getTotalCount = (count) => {
this.setState({
total: this.state.total + count
})
};
state = {
total: 0
};
render() {
const someData = [
{ name: "one", count: 200 },
{ name: "two", count: 100 },
{ name: "three", count: 50 }
];
return (
<div className="App">
{someData.map((nameAndCount, i) => {
return (
<SubComp
getTotal={this.getTotalCount}
name={nameAndCount.name}
count={nameAndCount.count}
key={i}
/>
);
})}
<h1>Total Count: {this.state.total}</h1>
</div>
);
}
}
export default App;
And Here is SubComp.js
import React, { Component } from 'react';
export default class SubComp extends Component {
calculateTotal = () =>{
this.props.getTotal(this.props.count);
}
render() {
return (
<div>
<p onClick={this.calculateTotal}> Name: {this.props.name} || Count: {this.props.count}</p>
</div>
)
}
};
Try to implement above and you will get exact scenario that how pass parameters works in reactjs on any DOM method.
I wrote a wrapper component that can be reused for this purpose that builds on the accepted answers here. If all you need to do is pass a string however, then just add a data-attribute and read it from e.target.dataset (like some others have suggested). By default my wrapper will bind to any prop that is a function and starts with 'on' and automatically pass the data prop back to the caller after all the other event arguments. Although I haven't tested it for performance, it will give you the opportunity to avoid creating the class yourself, and it can be used like this:
const DataButton = withData('button')
const DataInput = withData('input');
or for Components and functions
const DataInput = withData(SomeComponent);
or if you prefer
const DataButton = withData(<button/>)
declare that Outside your container (near your imports)
Here is usage in a container:
import withData from './withData';
const DataInput = withData('input');
export default class Container extends Component {
state = {
data: [
// ...
]
}
handleItemChange = (e, data) => {
// here the data is available
// ....
}
render () {
return (
<div>
{
this.state.data.map((item, index) => (
<div key={index}>
<DataInput data={item} onChange={this.handleItemChange} value={item.value}/>
</div>
))
}
</div>
);
}
}
Here is the wrapper code 'withData.js:
import React, { Component } from 'react';
const defaultOptions = {
events: undefined,
}
export default (Target, options) => {
Target = React.isValidElement(Target) ? Target.type : Target;
options = { ...defaultOptions, ...options }
class WithData extends Component {
constructor(props, context){
super(props, context);
this.handlers = getHandlers(options.events, this);
}
render() {
const { data, children, ...props } = this.props;
return <Target {...props} {...this.handlers} >{children}</Target>;
}
static displayName = `withData(${Target.displayName || Target.name || 'Component'})`
}
return WithData;
}
function getHandlers(events, thisContext) {
if(!events)
events = Object.keys(thisContext.props).filter(prop => prop.startsWith('on') && typeof thisContext.props[prop] === 'function')
else if (typeof events === 'string')
events = [events];
return events.reduce((result, eventType) => {
result[eventType] = (...args) => thisContext.props[eventType](...args, thisContext.props.data);
return result;
}, {});
}
I have below 3 suggestion to this on JSX onClick Events -
Actually, we don't need to use .bind() or Arrow function in our code. You can simple use in your code.
You can also move onClick event from th(or ul) to tr(or li) to improve the performance. Basically you will have n number of "Event Listeners" for your n li element.
So finally code will look like this:
<ul onClick={this.onItemClick}>
{this.props.items.map(item =>
<li key={item.id} data-itemid={item.id}>
...
</li>
)}
</ul>
// And you can access item.id in onItemClick method as shown below:
onItemClick = (event) => {
console.log(e.target.getAttribute("item.id"));
}
I agree with the approach mention above for creating separate React Component for ListItem and List. This make code looks good however if you have 1000 of li then 1000 Event Listeners will be created. Please make sure you should not have much event listener.
import React from "react";
import ListItem from "./ListItem";
export default class List extends React.Component {
/**
* This List react component is generic component which take props as list of items and also provide onlick
* callback name handleItemClick
* #param {String} item - item object passed to caller
*/
handleItemClick = (item) => {
if (this.props.onItemClick) {
this.props.onItemClick(item);
}
}
/**
* render method will take list of items as a props and include ListItem component
* #returns {string} - return the list of items
*/
render() {
return (
<div>
{this.props.items.map(item =>
<ListItem key={item.id} item={item} onItemClick={this.handleItemClick}/>
)}
</div>
);
}
}
import React from "react";
export default class ListItem extends React.Component {
/**
* This List react component is generic component which take props as item and also provide onlick
* callback name handleItemClick
* #param {String} item - item object passed to caller
*/
handleItemClick = () => {
if (this.props.item && this.props.onItemClick) {
this.props.onItemClick(this.props.item);
}
}
/**
* render method will take item as a props and print in li
* #returns {string} - return the list of items
*/
render() {
return (
<li key={this.props.item.id} onClick={this.handleItemClick}>{this.props.item.text}</li>
);
}
}
I have added code for onclick event value pass to the method in two ways . 1 . using bind method 2. using arrow(=>) method . see the methods handlesort1 and handlesort
var HeaderRows = React.createClass({
getInitialState : function() {
return ({
defaultColumns : ["col1","col2","col2","col3","col4","col5" ],
externalColumns : ["ecol1","ecol2","ecol2","ecol3","ecol4","ecol5" ],
})
},
handleSort: function(column,that) {
console.log(column);
alert(""+JSON.stringify(column));
},
handleSort1: function(column) {
console.log(column);
alert(""+JSON.stringify(column));
},
render: function () {
var that = this;
return(
<div>
<div>Using bind method</div>
{this.state.defaultColumns.map(function (column) {
return (
<div value={column} style={{height : '40' }}onClick={that.handleSort.bind(that,column)} >{column}</div>
);
})}
<div>Using Arrow method</div>
{this.state.defaultColumns.map(function (column) {
return (
<div value={column} style={{height : 40}} onClick={() => that.handleSort1(column)} >{column}</div>
);
})}
{this.state.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column;
return (<div><span>{externalColumnName}</span></div>
);
})}
</div>);
}
});
Below is the example which passes value on onClick event.
I used es6 syntax. remember in class component arrow function does not bind automatically, so explicitly binding in constructor.
class HeaderRows extends React.Component {
constructor(props) {
super(props);
this.handleSort = this.handleSort.bind(this);
}
handleSort(value) {
console.log(value);
}
render() {
return(
<tr>
{this.props.defaultColumns.map( (column, index) =>
<th value={ column }
key={ index }
onClick={ () => this.handleSort(event.target.value) }>
{ column }
</th>
)}
{this.props.externalColumns.map((column, index) =>
<th value ={ column[0] }
key={ index }>
{column[0]}
</th>
)}
</tr>
);
}
}
I guess you will have to bind the method to the React’s class instance. It’s safer to use a constructor to bind all methods in React. In your case when you pass the parameter to the method, the first parameter is used to bind the ‘this’ context of the method, thus you cannot access the value inside the method.
1. You just have to use an arrow function in the Onclick event like this:
<th value={column} onClick={() => that.handleSort(theValue)} >{column}</th>
2.Then bind this in the constructor method:
this.handleSort = this.handleSort.bind(this);
3.And finally get the value in the function:
handleSort(theValue){
console.log(theValue);
}
Using arrow function :
You must install stage-2:
npm install babel-preset-stage-2 :
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value=0
}
}
changeValue = (data) => (e) => {
alert(data); //10
this.setState({ [value]: data })
}
render() {
const data = 10;
return (
<div>
<input type="button" onClick={this.changeValue(data)} />
</div>
);
}
}
export default App;
Theres' a very easy way.
onClick={this.toggleStart('xyz')} .
toggleStart= (data) => (e) =>{
console.log('value is'+data);
}
class TableHeader extends Component {
handleClick = (parameter,event) => {
console.log(parameter)
console.log(event)
}
render() {
return (
<button type="button"
onClick={this.handleClick.bind(this,"dataOne")}>Send</button>
);
}
}
Coming out of nowhere to this question, but i think .bind will do the trick. Find the sample code below.
const handleClick = (data) => {
console.log(data)
}
<button onClick={handleClick.bind(null, { title: 'mytitle', id: '12345' })}>Login</button>
There are 3 ways to handle this :-
Bind the method in constructor as :-
export class HeaderRows extends Component {
constructor() {
super();
this.handleSort = this.handleSort.bind(this);
}
}
Use the arrow function while creating it as :-
handleSort = () => {
// some text here
}
Third way is this :-
<th value={column} onClick={() => that.handleSort} >{column}</th>
You can use your code like this:
<th value={column} onClick={(e) => that.handleSort(e, column)} >{column}</th>
Here e is for event object, if you want to use event methods like preventDefault() in your handle function or want to get target value or name like e.target.name.
There were a lot of performance considerations, all in the vacuum.
The issue with this handlers is that you need to curry them in order to incorporate the argument that you can't name in the props.
This means that the component needs a handler for each and every clickable element. Let's agree that for a few buttons this is not an issue, right?
The problem arises when you are handling tabular data with dozens of columns and thousands of rows. There you notice the impact of creating that many handlers.
The fact is, I only need one.
I set the handler at the table level (or UL or OL...), and when the click happens I can tell which was the clicked cell using data available since ever in the event object:
nativeEvent.target.tagName
nativeEvent.target.parentElement.tagName
nativeEvent.target.parentElement.rowIndex
nativeEvent.target.cellIndex
nativeEvent.target.textContent
I use the tagname fields to check that the click happened in a valid element, for example ignore clicks in THs ot footers.
The rowIndex and cellIndex give the exact location of the clicked cell.
Textcontent is the text of the clicked cell.
This way I don't need to pass the cell's data to the handler, it can self-service it.
If I needed more data, data that is not to be displayed, I can use the dataset attribute, or hidden elements.
With some simple DOM navigation it's all at hand.
This has been used in HTML since ever, since PCs were much easier to bog.
When working with a function as opposed to a class, it's actually fairly easy.
const [breakfastMain, setBreakFastMain] = useState("Breakfast");
const changeBreakfastMain = (e) => {
setBreakFastMain(e.target.value);
//sometimes "value" won't do it, like for text, etc. In that case you need to
//write 'e.target/innerHTML'
}
<ul onClick={changeBreakfastMain}>
<li>
"some text here"
</li>
<li>
"some text here"
</li>
</ul>
I'd do it like this:
const HeaderRows = props => {
const handleSort = value => () => {
}
return <tr>
{props.defaultColumns.map((column, i) =>
<th key={i} onClick={handleSort(column)}>{column}</th>)}
{props.externalColumns.map((column, i) => {
// Multi dimension array - 0 is column name
const externalColumnName = column[0]
return (<th key={i}>{externalColumnName}</th>)
})}
</tr>
}

Categories