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!





Thank u so much, all works!
– Ksym
Aug 27 at 20:06



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)