Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JSX: How to set props to placeholder attribute

I have an input tag and I'm trying to set the placeholder's contents to the component's props. After compiling JSX and running it in the browser, the placeholder does not show up at all. It's also not throwing any errors. How can I do this?

<input type="text" onChange={this.props.handleChange} placeholder={this.props.name} />
like image 928
astone Avatar asked Jan 14 '15 19:01

astone


People also ask

How do you give a placeholder in React?

Use the placeholder prop to set a placeholder on an input field in React, e.g. <input type="text" placeholder="Your first name" /> . The placeholder text of an input field is shown until the user types something in the field. Copied!

What is placeholder in React JS?

A placeholder is used to reserve space for content that soon will appear in a layout. Placeholders can include PlaceholderParagraph , PlaceholderHeader , and PlaceholderImage to let you format the loaders to emulate the content being loaded.

How can props be defined within JSX?

createElement() function calls you basically already have a understanding of how React node attributes/props work. However, since JSX is used to express XML-like nodes that get turned into HTML, attribute/props are defined by adding the attributes/props to JSX expressions as name-value attributes.


1 Answers

There seems to be nothing wrong with this code in the child component. The placeholder should show up just fine, as you implemented it.

Here is how I have it set in the parent:

import React, { Component } from 'react';
import Title from'./Title';
import TestList from'./TestList';

export default class Layout extends Component {
    constructor() {
        super();
        this.state = {
          title: 'Moving Focus with arrow keys.',
          placeholder:'Search for something...'
        };
    }

    render() {    
        return (
            <div >
                <Title title={ this.state.title } />
                <p>{ this.getVal() }</p>
                <TestList placeholderText={this.state.placeholder} />
            </div>
        );
    }
}

Here is how I display it in the child:

import React, { Component } from 'react';

export default class TestInput extends Component {
    constructor(props){
        super(props);
    };

    render() {
        return (
            <div>
              <input type="search" placeholder={this.props.placeholderText} />
            );
        } 
    }
}

Bit of a late reply but hope it helps! :-)

like image 162
edlee Avatar answered Nov 04 '22 14:11

edlee