0

When clicking on the ancestry tag, I want the links below to open using window.open().

I know that props can easily be passed to children but this does not help.

The child elements looks like this:

import React from 'react';

class FramePageFaveTagFave extends React.Component {

  constructor(props) {
    super(props);
  }

  bookmarkClicked (url) {
    window.open(url, '_blank')
  }

  render () {
    let bm = this.props.bookmark;
    let tagClicked = this.props.tagClicked;

    return (
      <div className='bookmark_div' id={bm.id + 'a'} onClick={() => {this.bookmarkClicked(bm.url)}} >
        <img className='bookmark_image' id={bm.id + 'c'} src={'../_favicons/' + bm.favicon_local}/>
        <a className='bookmark_link' id={bm.id + 'b'} href={bm.url} target='_blank'
          onClick={()=>{e.preventDefault();}}>
          {bm.title}
        </a>
      </div>
    );
  }
}

export default FramePageFaveTagFave;
  • So whats the issue ? – klugjo Jan 05 '18 at 02:58
  • I think this [SO answer](https://stackoverflow.com/a/37950970/6053299) might be helpful, the idea is to use `refs` which will allow you to store references to you child components in the parent component, then you will be able to call methods of your child components from the parent, you can check [react docs](https://reactjs.org/docs/refs-and-the-dom.html) about refs. – margaretkru Jan 05 '18 at 08:45
  • When the parent is clicked, you can pass props to its children elements to notify them what to do. – Code-Apprentice Jan 07 '18 at 19:16

1 Answers1

0

A good rule of thumb is to think in callbacks when doing this sort of work. The parent can pass a prop down called onBookmarkClicked which is a function that takes a url. Maybe this:

onBookmarkCalled(url) {
   window.open(url, '_blank')
}

<ChildBookmark onBookMarkCalled={this.onBookmarkCalled} />

And you do the exact same thing in the child except instead of this.bookmarkClicked you can do onClick={() => this.props.onBookmarkClicked(url)}

ZekeDroid
  • 7,089
  • 5
  • 33
  • 59
  • Ah, that won't really work. Instead, you'd need to use state. For example, when something is clicked in the parent, set a state variable (maybe, `bookmarkClicked: 'some.url.com'`) and then pass this to the child. The child should assume that when there is a value on this prop (and if it is different than the previous) it's a "click". It's not super clean and it feels like there's a better way to do this but it would work. – ZekeDroid Jan 05 '18 at 04:05
  • It feels like we're missing something here. There may be a better way of doing it if it feels like it won't scale. It's possible that React isn't good for your use case either and that you really would need to use DOM events but that seems unlikely – ZekeDroid Jan 05 '18 at 04:39