Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering "a" with optional href in React.js

I need to render a table with a link in one of the columns, and searching for a most elegant way to do it. My main problem is - not all table rows are supplied with that link. If link is present - I need that "a" tag rendered. If not - no need for "a" tag at all. Generally speaking I would like react to handle that choice (render vs not render) depending on this.state.

This is what I have at the moment.

React.createClass({
    getInitialState: function () {
        return {
            pipeline: this.props.data.pipeline,
            liveUrl: this.props.data.liveUrl,
            posted: this.props.data.created,
            expires: this.props.data.end
        };
    },

    render: function () {
        return (
            <tr className="posting-list">
                <td><a href={this.state.liveUrl} target="_blank">{this.state.pipeline}</a></td>
                <td>Posted</td>
                <td>
                    <input className="datepicker" type="text" value={this.state.posted}/>
                </td>
                <td>
                    <input className="datepicker" type="text" value={this.state.expires}/>
                </td>
                <td>UPDATE, DELETE</td>
            </tr>
        );
    }
});

This results is DOM element :

<a href="" target="_blank" data-reactid=".0.6.0.0.1:1.0.0">XING_batch</a>

This is not acceptable solution for me, because those blank hrefs are still clickable. I also tried adding some logic to getInitalState( liveUrl: (this.props.data.liveUrl !== "") ? this.props.data.liveUrl : "javascript:void;", ), which worked fine, but looks weird, and adds errors in console(Uncaught SyntaxError: Unexpected token ;)

The only way I've got left is creating 2 different components for

like image 591
Arthem Dulchevsky Avatar asked Apr 07 '15 04:04

Arthem Dulchevsky


People also ask

How do you render a different component in React on button click?

To show or hide another component on click in React: Set the onClick prop on an element. When the element is clicked, toggle a state variable that tracks if the component is shown. Conditionally render the component based on the state variable.

Can we use onClick in anchor tag in React JS?

To set an onClick listener on a link in React: What is this? The code snippet shows how to set an onClick event listener on a React router Link or an anchor element. Every time the link is clicked, the handleClick function is invoked.


1 Answers

It's just JavaScript, so you can use any logic you like, e.g.:

<td>
    {this.state.liveUrl  
     ? <a ...>{this.state.pipeline}</a> 
     : this.state.pipeline}
</td>
like image 56
Brigand Avatar answered Oct 13 '22 09:10

Brigand