Bitter-jackfruit
Bitter-jackfruit

Reputation: 85

How to implement this without Refs and DOM Manipulation

Since onChange does not work for < p > tags , how can I implement the below functionality using states? I can aslo use refs but that and the DOM manipulation below is the last resort option and not ideal for a react application.

Parent class:

 saveNoteAfterEdit(note_id){
        //some code
        const newNote = document.getElementById(note_id).textContent; //works
  }

Child class:

const displayNotes = notesList.map( (note,note_id) =>
  <p id={ note_id } } > {note} </p>
  <button onClick = { () => this.props.saveNoteAfterEdit(note_id) }> Save </button>
//some code
    );

Upvotes: 1

Views: 178

Answers (1)

95faf8e76605e973
95faf8e76605e973

Reputation: 14191

Since each note has a corresponding note_id, you could find the corresponding note_id correlated with the p concerned that you are trying to get the value of

const data = [
  {
    note_id: 1,
    note: "hello"
  },
  {
    note_id: 2,
    note: "note2"
  }
]

function App() {

  const [notesList, setNotesList] = React.useState(data);

  function saveNoteAfterEdit(note_id){
    const {note: newNote} = notesList.find((note)=>note.note_id == note_id)
    console.log(newNote);
  }

  return (
    notesList.map(({note, note_id})=>(
      <div>
        <p id={note_id} key={note_id}>{note}</p>
        <button onClick={()=>saveNoteAfterEdit(note_id)}>Do Something</button>
      </div>
    ))
  )
}

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

<div id="root"></div>

Upvotes: 1

Related Questions