Search code examples
reactjsrefstyled-components

How get refs.value in styled-component React?


I want get ref value of input, without styled component:

<form  role='form' method='POST' onSubmit= {::this.onSubmit}>               
<input id='name' type='text' ref='name' name='name'  required/>
<button> Register</button></form>


 onSubmit(e){
    e.preventDefault();
    console.log(this.refs.name.value)...}

How get ref.value in styled-component?

  <form  role='form' method='POST' onSubmit= {::this.onSubmit}>               
<StyledInput innerRef={name => { this.input = name }} id='name' type='text' name='name' />
<button> Register</button></form>  

 onSubmit(e){
e.preventDefault();
console.log(this.input);....}

Solution

  • Adding innerRef={name => { this.input = name }} makes the input node available through this.input

    console.log(this.input.value)
    

    You could get the value from the Event without using ref

    onSubmit(e) {
        console.log(e.target.value)
    }
    

    More details about React forms.

    Demo component:

    import React from "react";
    import styled from "styled-components";
    
    const InputStyled = styled.input`
      background: lightgreen;
    `;
    
    class Test extends React.Component {
      onChange = e => {
        console.log(this.input.value);
        console.log(e.target.value);
      };
      render = () => {
        return (
          <InputStyled
            onChange={this.onChange}
            innerRef={input => (this.input = input)}
          />
        );
      };
    }
    
    export default Test;

    Hope it helps!