Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get innerHTML when clicking a button in React js?

I'm trying to use material-ui-flat-pagination. Since the library seems not to provide page number when clicking previous or next button, I'm trying to get the value by myself. It provides only one onClick prop, so I used event.target to get the value that I click.

enter image description here

event.target shows the above tag, and I need the value 3 inside the span tag. How can I get the value in React js? Am I approaching the right way to get the page number with the library material-ui-flat-pagination?

like image 882
Jae P. Avatar asked Oct 26 '18 22:10

Jae P.


1 Answers

I am sorry for not adding a comment i don't have the reputation yet. x will note you the number you are asking but don't try to update offset with x cause of the offset calculation defined on core.ts of the module.

export const getOffset = (page: number, limit: number): number => { const offset = (page - 1) * limit; return offset < 0 ? 0 : offset; };

Although you can try to get the HTML you want by parsing the event. a trick is to match a case with the params that the interface provide like next or previous labels

e.target.innerText
e.currentTarget.childNodes[0].innerText

*mind it is a string so care your number comparisons

import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@material-ui/core/CssBaseline";
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";
import Pagination from "material-ui-flat-pagination";

const theme = createMuiTheme();

class Example extends React.Component {
constructor(props) {
    super(props);
    this.state = { offset: 0, limit: 3, total: 132, calc: 1, nlabel: ">>", plabel: "<<" };
}

handleClick(e, offset) {
    let y = e.target.innerText; 
    //let y =e.currentTarget.childNodes[0].innerText;

    if (y === this.state.plabel) y = Number(this.state.calc) - 1;
    if (y === this.state.nlabel) y = Number(this.state.calc) + 1;
    let x = offset / this.state.limit + 1;
    console.log("x:" + x + " - y:" + y);
    this.setState({ offset, calc: y });
}

render() {
    return (
        <MuiThemeProvider theme={theme}>
            <div>{this.state.offset}</div>
            <div>{this.state.calc}</div>
            <CssBaseline />
            <Pagination
                limit={this.state.limit}
                offset={this.state.offset}
                total={this.state.total}
                onClick={(e, offset) => this.handleClick(e, offset)}
                nextPageLabel={this.state.nlabel}
                previousPageLabel={this.state.plabel}
            />
        </MuiThemeProvider>
    );
}
}

ReactDOM.render(<Example />, document.getElementById("root"));
like image 158
JVal aka SolidSnake Avatar answered Oct 31 '22 16:10

JVal aka SolidSnake