0

Im new to React, I have built a dropdown in ES6 react which shows one image and a text line. It works fine and fetches the data from a data array and shows it. Now I have to do one thing: when the user clicks on an option in the dropdown, the dropdown closes and shows the selected option instead the original one [0]. I tried with javascript sentences taking the innerHTHML, but that is not the way to do it.

Here is the code:

import React from "react";

class StatusBarCompaniesView extends React.Component {

    mixins: [ClickAwayable]


    constructor(props) {
        super(props)
        this.state = {dropdown: false}
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick() {
        this.setState({ dropdown: !this.state.dropdown });
    }

    clickSelectOption(e){
        console.log(e.target);
        e.stopPropagation();
        var valueNode = this.refs.dropDownValue.getDOMNode();
        valueNode.innerHTML = e.target.innerHTML;
        valueNode.setAttribute('data-value',e.target.getAttribute('data-value'))
    }

    render() {
        var me = this;
        var company_items = [
           { payload: '1', imageurl: 'images/avatar.png',       text: 'Burger Apps, SL' },
           { payload: '2', imageurl: 'images/avatar-apple.png', text: 'Apple Computer Inc' },
           { payload: '3', imageurl: 'images/avatar-hp.png',    text: 'Hewlett Packard' },
           { payload: '4', imageurl: 'images/avatar-apple.png', text: 'Eyects Systems' }
        ];

        var cx = require('classnames');
        var dropdown = cx ({
            'aui-profit-statusbar-companies-dropdown-container' : true,
            'dropdown' : this.state.dropdown
        });

        var cx = require('classnames');
        var selected = cx ({
            'aui-profit-statusbar-companies-container' : true,
            'selected' : this.state.dropdown
        });

    return (
        <div className={selected} onClick={this.handleClick}>
        <div ref="dropDownValue">
            <div className="aui-profit-statusbar-selected-company-logo"><img src={company_items[0].imageurl}/></div>
            <div className="aui-profit-statusbar-selected-company-name">{company_items[0].text}</div>
        </div>
            <div className={dropdown}>
                    {company_items.map(function(option, index){
                        return (
                            <div key={index} className="option" data-value={option.payload} onClick={me.clickSelectOption.bind(me)}>
                                <div className="aui-profit-statusbar-companies-logo"><img src={option.imageurl}/></div>
                                <div className="aui-profit-statusbar-companies-name">{option.text}</div>
                            </div>

                        );
                    })}         
            </div>
        </div>
    );
  }
};


module.exports = StatusBarCompaniesView;

Any kind of help is welcome! thanks!

3
  • you have to set selected . and make a state selected Item . Set that state on clicking of that particular load Commented Apr 30, 2015 at 7:29
  • Hi, thanks, im wondering what you mean, not sure how to do this Commented Apr 30, 2015 at 7:36
  • 1
    selected is one property in select option . which should be equal to your some state. and you have to change that state Commented Apr 30, 2015 at 7:39

2 Answers 2

1

When you create the dropdown option you already know its value, so just bind with that, so the callback is called with the correct parameter, saving you from inspecting the DOM, eg:

in render()

{company_items.map(function(option, index){
    return (
        <div key={index} className="option" onClick={me.clickSelectOption.bind(me, option.payload)}>
            <div className="aui-profit-statusbar-companies-logo"><img src={option.imageurl}/></div>
            <div className="aui-profit-statusbar-companies-name">{option.text}</div>
        </div>

    );
})}  

Then in the handler:

clickSelectOption(payload){
    console.log(payload);
    this.setState({ selected: payload });
}
Sign up to request clarification or add additional context in comments.

4 Comments

ok console.logs show the number of the clicked playload (option) now how i can sore the selected item in state?? im very lost with react, i only know how to do the basics
ok now im storing the selected item in to a state this way: clickSelectOption(playload){ console.log(playload); this.state.selected = playload console.log(this.state.selected) }
you need to use setState()
Finally i did it but with a help of a work mate, you was right, im not a programmer, im a pure front end developer and i learning react. its hard at the beginning
1

This is the final componet, thanks guys:

import React from "react";

class StatusBarCompaniesView extends React.Component {

    mixins: [ClickAwayable]


    constructor(props) {
        super(props)
        this.state = {dropdown: false, selectedOption: 0}
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick() {
        this.setState({ dropdown: !this.state.dropdown });
    }

    componentWillMount() {
        this._closeMenuIfClickedOutside = function(event) {
            if (!this.state.dropdown) {
                return;
            }
            var menuElem = this.refs.selectMenuContainer.getDOMNode();

            var eventOccuredOutsideMenu = this.clickedOutsideElement(menuElem, event);

            // Hide dropdown menu if click occurred outside of menu
            if (eventOccuredOutsideMenu) {
                this.setState({
                    dropdown: false
                }, this._unbindCloseMenuIfClickedOutside);
            }
        }.bind(this);

        this._bindCloseMenuIfClickedOutside = function() {
            document.addEventListener('click', this._closeMenuIfClickedOutside);
        };

        this._unbindCloseMenuIfClickedOutside = function() {
            document.removeEventListener('click', this._closeMenuIfClickedOutside);
        };
    }

    clickedOutsideElement(element, event) {
        var eventTarget = (event.target) ? event.target : event.srcElement;
        while (eventTarget != null) {
            if (eventTarget === element) return false;
            eventTarget = eventTarget.offsetParent;
        }
        return true;
    }

    clickSelectOption(playload){
        console.log(playload);
        this.state.selectedOption = playload
        console.log(this.state.selectedOption)
    }

    render() {
        var me = this;
        var company_items = [
           { payload: '0', imageurl: 'images/avatar.png',       text: 'Burger Apps, SL' },
           { payload: '1', imageurl: 'images/avatar-apple.png', text: 'Apple Computer Inc' },
           { payload: '2', imageurl: 'images/avatar-hp.png',    text: 'Hewlett Packard' },
           { payload: '3', imageurl: 'images/avatar-apple.png', text: 'Eyects Systems' }
        ];

        var cx = require('classnames');
        var dropdown = cx ({
            'aui-profit-statusbar-companies-dropdown-container' : true,
            'dropdown' : this.state.dropdown
        });

        var cx = require('classnames');
        var selected = cx ({
            'aui-profit-statusbar-companies-container' : true,
            'selected' : this.state.dropdown
        });

    return (
        <div className={selected} onClick={this.handleClick}>
        <div ref="dropDownValue">
            <div className="aui-profit-statusbar-selected-company-logo"><img src={company_items[this.state.selectedOption].imageurl}/></div>
            <div className="aui-profit-statusbar-selected-company-name">{company_items[this.state.selectedOption].text}</div>
        </div>
            <div className={dropdown} ref="selectMenuContainer">
                {company_items.map(function(option, index){
                    return (
                        <div key={index} className="option" onClick={me.clickSelectOption.bind(me, option.payload)}>
                            <div className="aui-profit-statusbar-companies-logo"><img src={option.imageurl}/></div>
                            <div className="aui-profit-statusbar-companies-name">{option.text}</div>
                        </div>
                    );
                })}         
            </div>
        </div>
    );
  }
};


module.exports = StatusBarCompaniesView;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.