Yuqin Xu
Yuqin Xu

Reputation: 187

JS How to get id of current section?

I wonder how to get the id property of section itself, the following example is what I am trying to realize:
I have a mapping dictionary predefined, and I hope the defaultValue of section to be mapping['id']. The problem is the id might be changing so I need to get the current id of each section.

mapping = {'1':'a', '2':'b', '3':'c'}

    <div> 
        <select defaultValue=mapping[{id_of_this_select_object}] id='1' />
    </div> 

The result should be:

        <div> 
            <select defaultValue='a' id='1' />
        </div> 

Thanks!

Upvotes: 1

Views: 308

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58543

This is how you can do that :

<div> 
   {Object.keys(mapping).map(k => <select defaultValue={mapping[k]} id={k} />) }
</div>

You can check this by running below code snippet :

const { useState , useEffect } = React;

const App = () => {

  const mapping = {'1':'a', '2':'b', '3':'c'};

  return (
    <div>
      
      <p>As answer to your question :</p>
      {Object.keys(mapping).map(k => <div><select defaultValue={mapping[k]} id={k} key={mapping[k]} /></div>) }
  
      <p>But , I think you are expecting something like this :</p>
      <select>
        { Object.keys(mapping).map(k => <option defaultValue={mapping[k]} id={k} value={k} key={mapping[k]}>{mapping[k]}</option>) }
      </select>    
    </div>


  );
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>

Upvotes: 1

ABGR
ABGR

Reputation: 5205

Since you're using React, you could just do this:

mapping = {'1':'a', '2':'b', '3':'c'}

<div> 
     {
       Object.keys(mapping).map(i=>{
          return (
            <select defaultValue={mapping[i]} id={i} />
          )
        })
     }
</div> 

UPDATE: If you just want select's default value to be based on mapping. You could do something like this:

  state:{
   defaultId: 1
  }
  someMethodChangingDefaultId(currentId){
    this.setState({id: currentId})
  }

Then, in .render:

  <select defaultValue={mapping[this.state.defaultId]} id={this.state.defaultId} />

Upvotes: 1

Related Questions