javascript - React dynamically create buttons based on number of results - Stack Overflow

I am working in a Spring application that uses react. Currently I have a json that contains several use

I am working in a Spring application that uses react. Currently I have a json that contains several users based on certain criteria. The number of users can vary, but I would like to create several buttons for each user returned that links to the users profile. the url is just '/profile/username'

format of json

[{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipcode":"98077","firstname":"cat","password":"abc123","sitterFlag":"true","ownerFlag":"false","lastname":"sitter","username":"catsitter","preferredPet":"Cat"},"momento":"[email protected]"},"password":"$2a$10$ltnL.mFqo7hatj69Ls76xeegjhEX0D4At9m1rlBHbQtDrV8MdSeAS","momento":"[email protected]"},{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipcode":"98077","firstname":"test","password":"abc123","sitterFlag":"false","ownerFlag":"false","lastname":"pets","username":"testpets"},"momento":"[email protected]"},"password":"$2a$10$wDhS6Mb8syhC0YIqgVG2qu8J6lA.1T.UprMYwAX6O7Xb3YMhgX3bO","momento":"[email protected]"},{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipCode":"98077","firstname":"test","password":"abc123","lastname":"sitter","username":"testsitter"},"momento":"[email protected]"},"password":"$2a$10$DuIeWFSzhtAjX3lr8xBNiu2kV9kAJ/PQ6pB/EzkB7FkGWfRbwxkzy","momento":"[email protected]"},{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipCode":"98077","firstname":"sit","password":"abc123","lastname":"sitter","username":"imasitter"},"momento":"[email protected]"},"password":"$2a$10$2NKOQkGZO/jUer3UjNGzdugUhkMV1pJ1eT8NQjSPRto9/cRdm56sO","momento":"[email protected]"},{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipCode":"98077","firstname":"a","password":"abc123","lastname":"sitter","username":"asitter"},"momento":"[email protected]"},"password":"$2a$10$8x1uVqR28x5rwNrydieSyu1ILifBJ5n0dUsZI5tJ6MoUWMqXxrmeq","momento":"[email protected]"}]

I currently have it working if I hard code for each user:

<div className="container padded">
    <div className="row">
        <div className="col-6 offset-md-3">
            <h2>Suggested Sitters</h2>
            <button onClick={() => this.suggestSitter(this.props.user.principal)}>Click</button>
            <hr/>
            <div>
                Sitters:
            </div>
            <Link to={this.setProfile(this.state.sitter ? this.state.sitter[1].user.attributes.username: ' ')} >
                <button type="button">{this.state.sitter ? this.state.sitter[1].user.attributes.username: ' '}</button>
            </Link>
        </div>
    </div>
</div>

the setProfile works like this:

setProfile(theUser) {
    return '/profile/' + theUser;
}

Clicking a button will redirect to that user's profile page.

So basically, instead of hardcoding n buttons, I would like to dynamically create n buttons and each will link to '/profile/username/ for each user returned.

suggestSitter function:

suggestSitter(user){
        var _this = this;
        console.log('user', user);
        axios.get('/api/user/suggest_sitter', { params: { principal: user } })
            .then(function(response) {
                console.log('Response: ' + JSON.stringify(response));
                _this.setState({
                    sitter: response
                });
            })
            .catch(function (e) {
                console.log('Error: ' + e);
            });
    }

I am working in a Spring application that uses react. Currently I have a json that contains several users based on certain criteria. The number of users can vary, but I would like to create several buttons for each user returned that links to the users profile. the url is just '/profile/username'

format of json

[{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipcode":"98077","firstname":"cat","password":"abc123","sitterFlag":"true","ownerFlag":"false","lastname":"sitter","username":"catsitter","preferredPet":"Cat"},"momento":"[email protected]"},"password":"$2a$10$ltnL.mFqo7hatj69Ls76xeegjhEX0D4At9m1rlBHbQtDrV8MdSeAS","momento":"[email protected]"},{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipcode":"98077","firstname":"test","password":"abc123","sitterFlag":"false","ownerFlag":"false","lastname":"pets","username":"testpets"},"momento":"[email protected]"},"password":"$2a$10$wDhS6Mb8syhC0YIqgVG2qu8J6lA.1T.UprMYwAX6O7Xb3YMhgX3bO","momento":"[email protected]"},{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipCode":"98077","firstname":"test","password":"abc123","lastname":"sitter","username":"testsitter"},"momento":"[email protected]"},"password":"$2a$10$DuIeWFSzhtAjX3lr8xBNiu2kV9kAJ/PQ6pB/EzkB7FkGWfRbwxkzy","momento":"[email protected]"},{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipCode":"98077","firstname":"sit","password":"abc123","lastname":"sitter","username":"imasitter"},"momento":"[email protected]"},"password":"$2a$10$2NKOQkGZO/jUer3UjNGzdugUhkMV1pJ1eT8NQjSPRto9/cRdm56sO","momento":"[email protected]"},{"user":{"principal":"[email protected]","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"[email protected]","zipCode":"98077","firstname":"a","password":"abc123","lastname":"sitter","username":"asitter"},"momento":"[email protected]"},"password":"$2a$10$8x1uVqR28x5rwNrydieSyu1ILifBJ5n0dUsZI5tJ6MoUWMqXxrmeq","momento":"[email protected]"}]

I currently have it working if I hard code for each user:

<div className="container padded">
    <div className="row">
        <div className="col-6 offset-md-3">
            <h2>Suggested Sitters</h2>
            <button onClick={() => this.suggestSitter(this.props.user.principal)}>Click</button>
            <hr/>
            <div>
                Sitters:
            </div>
            <Link to={this.setProfile(this.state.sitter ? this.state.sitter[1].user.attributes.username: ' ')} >
                <button type="button">{this.state.sitter ? this.state.sitter[1].user.attributes.username: ' '}</button>
            </Link>
        </div>
    </div>
</div>

the setProfile works like this:

setProfile(theUser) {
    return '/profile/' + theUser;
}

Clicking a button will redirect to that user's profile page.

So basically, instead of hardcoding n buttons, I would like to dynamically create n buttons and each will link to '/profile/username/ for each user returned.

suggestSitter function:

suggestSitter(user){
        var _this = this;
        console.log('user', user);
        axios.get('/api/user/suggest_sitter', { params: { principal: user } })
            .then(function(response) {
                console.log('Response: ' + JSON.stringify(response));
                _this.setState({
                    sitter: response
                });
            })
            .catch(function (e) {
                console.log('Error: ' + e);
            });
    }
Share Improve this question edited Apr 25, 2018 at 7:22 Jakeeln asked Apr 25, 2018 at 6:31 JakeelnJakeeln 3531 gold badge4 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

You can map the data to an array of Link (provide an unique key for it too):

{this.state.sitter.map((e) => (
  <Link key={e.someUniqueProperty} to={this.setProfile(e.user.attributes.username)}>
    <button type="button">{e.user.attributes.username}</button>
  </Link>
))}

Suppose your data is:

const data = [
  {user: {...}, attribute: {...}},
  {user: {...}, attribute: {...}},
  ...
]

Now, you can follow these steps:

Create a stateless/stateful ponent(depending on your use case): UserButton or any other meaningful name:

const UserButton = () => (
    <div className="container padded">
        <div className="row">
            <div className="col-6 offset-md-3">
                /*...Add your remaining JSX....*/
            </div>
        </div>
    </div>
)

Now in your parent ponent(from where you are actually rendering the data), you can do the following:

renderUserButtons = () => {
    return data.map((userData) => (
        <UserButton key="Some-unique-id-can-be-anything" PASS_YOUR_PROPS_HERE/>
    ))
}

render() {
    return (
        <div>
            ...
            {this.renderUserButtons()}
            ...
        </div>
    );
}

Obviously, you don't need multiple ponents for this, but splitting it into smaller ponents looks good, easier to maintain and easier to test. Again it's my personal preference. You can use the convention whatever is best for you.

To create any UI ponent from some array, you can always use map function like below.

Array of JSON Object

let users = [{"name":"ABC"},{"name":"DEF"},{"name":"GHI"}];

Map Function

let userList = users.map((user,index)=>{return (<div>{index} - {user.name}<div>)})

this will give you following output:

0 - ABC 1 - DEF 2 - GHI

in map function user is the reference to one by one users from the array. Index is the key for each value from array (ex. 0,1,2....).

We are returning a JSX object from the return statement.

You can now use userList variable in render's return. Like below..

render(){ let userList = "...."; return(<div>{userList}</div>

I hope this would help.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744397408a4572212.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信