How get refs.value in styled-component React?
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);....
2 Answers
2
Adding innerRef=name => this.input = name
makes the input node available through this.input
innerRef=name => this.input = name
this.input
console.log(this.input.value)
You could get the value from the Event
without using ref
Event
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!
Not sure how StyledInput works with refs, but you can access a ref node with the .current key of the ref object.
https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thank u so much, all works!
– Ksym
Aug 27 at 20:06